Articles in this section
Category / Section

How to change column's datasource dynamically in JS Grid?

2 mins read

This KB showcase the example to update the column’s data source dynamically.

Solution

We can update the column’s data source alone without refreshing the grid data source by using columns method of ejGrid.

Step 1: Render the Grid control and External Button.

HTML

 
<button id="btn2">Click</button>
<div id="FlatGrid"></div>
 

JS

 
$(function () {
           $("#FlatGrid").ejGrid({
                dataSource: window.gridData,
                allowPaging: true,
                editSettings: { allowAdding: true, allowDeleting: true, allowEditing: true },
                toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Edit, ej.Grid.ToolBarItems.Delete, ej.Grid.ToolBarItems.Update, ej.Grid.ToolBarItems.Cancel] },
                columns: [
                     { field: "OrderID", isPrimaryKey: true, headerText: "Order ID", width: 90},
                     { field: "ShipCity", headerText: "City", width: 90 },
                     { field: "ShipCountry", headerText: "Country",  width: 90, editType: ej.Grid.EditingType.Dropdown  }
                ]
            });
        });

MVC

 
<button id="btn2">Click</button>
 
@(Html.EJ().Grid<object>("FlatGrid")
            .Datasource((IEnumerable<object>)ViewBag.datasource)
            .AllowPaging()    
            .EditSettings(edit => edit.AllowEditing().AllowAdding().AllowDeleting())
           .ToolbarSettings(toolbar =>
             {
               toolbar.ShowToolbar().ToolbarItems(items =>
                {
                  items.AddTool(ToolBarItems.Add);
                  items.AddTool(ToolBarItems.Edit);
                  items.AddTool(ToolBarItems.Delete);
                  items.AddTool(ToolBarItems.Update);
                  items.AddTool(ToolBarItems.Cancel);
        });
    })
       .Columns(col =>
          {
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(90).Add();
            col.Field("ShipCity ").HeaderText("City”).Width(90).Add();
            col.Field("ShipCountry ").HeaderText("Country”).EditType(EditingType.DropdownEdit) Width(90).Add();
 
        }))
[Controller]
namespace EJGrid.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var DataSource = new NorthwindDataContext().OrdersViews.ToList();
            ViewBag.data = DataSource;
            return View();
        }        
    }
}

 

ASP

 
<button id="btn2">Click</button>
 
<ej:Grid ID="FlatGrid" runat="server"  AllowPaging="True" >
            <Columns>
                <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="True"  Width="90" />
                 <ej:Column Field="ShipCity" HeaderText="City"  Width="90" />
                 <ej:Column Field="ShipCountry" HeaderText="Country" EditType="Dropdown"  Width="90"/>
            </Columns>
  <EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True"></EditSettings>
            <ToolbarSettings ShowToolbar="True" ToolbarItems="add,edit,delete,update,cancel "></ToolbarSettings>
 
        </ej:Grid>
 
 
[CS]
public partial class _Default : Page
{    
    protected void Page_Load(object sender, EventArgs e)
    {
            this.FlatGrid.DataSource = new NorthwindDataContext().Orders;
            this.FlatGrid.DataBind();
    }
}

 

.Net core

 
<button id="btn2">Click</button>
 
 
<ej-grid id="FlatGrid " allow-paging="true" datasource=" ViewBag. DataSource " >
    <e-edit-settings allow-adding="true" allow-editing="true" allow-deleting="true" ></e-edit-settings>
    <e-toolbar-settings show-toolbar="true" toolbar-items='@new List<string> {"add","edit","update","cancel"}' />
    <e-columns>
        <e-column field="OrderID" is-primary-key="true" header-text="Order ID" width="90"></e-column>
        <e-column field="ShipCity" header-text="City" width="90"></e-column>
        <e-column field="ShipCountry" header-text="Country" width="90"></e-column>  
    </e-columns>
</ej-grid>
 

 

Angular

<input id="btn2" (ejclick)="buttonClick($event)" text="Click "type="button" ej-button/> 
<ej-grid id="FlatGrid" #FlatGrid [allowPaging]="true" [dataSource]="gridData"
 [toolbarSettings]="toolbarItems" [editSettings]="editSettings">
    <e-columns>
            <e-column field="OrderID" headerText="Order ID" [isPrimaryKey]="true"
 width="90" ></e-column>
            <e-column field="ShipCity" headerText="City" textAlign="left" 
width="90"></e-column>
            <e-column field="ShipCountry" headerText="Country" editType="dropdownedit" 
width="90" ></e-column>        
    </e-columns>
</ej-grid>
 

 

TS

export class AppComponent {    
@ViewChild('FlatGrid') public FlatGrid: GridComponent;
    public gridData;
    public editSettings;
    public toolbarItems;
        constructor()
        {
          this.gridData = (window as any).gridData;
          this.editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true,editMode : "normal" };
          this.toolbarItems={ showToolbar : true, toolbarItems : ["add", "edit", "delete", "update", "cancel"]};     
        }
        buttonClick(e) {
            var refreshDataSource = []; //New data source dropdownlist 
            for (i = 0; i < 5; i++) 
            {
                var cityOption = {
                    "text" : "City " + i,
                    "value" : "City " + i
                };
                refreshDataSource.push(cityOption);
            }
            // Change ShipCountry item options here.    
            for (var i = 0; i < this.FlatGrid.widget.model.columns.length; i++)
            {
                if (this.FlatGrid.widget.model.columns[i].field == "ShipCountry")
                {
                    // Change "ShipCountry" options dynamically.    
                    this.FlatGrid.widget.model.columns[i].dataSource = refreshDataSource;
                   /*After updating the columns dropdown datasource pass the columns it to the grid`s columns method to update them.*/
                    this.FlatGrid.widget.columns(this.FlatGrid.widget.model.columns[i],"update")
                    break;
                }
            }
         }
    
     }

 

Step 2: Change the column’s dataSource in the button click event using columns method of ejGrid, here we have changed the ‘ShipCountry’ column’s dataSource.

<script>
      $("#btn2").ejButton({
                  click: function (args) {
                      var refreshDataSource = []; //New data source dropdownlist 
                      for (i = 0; i < 5; i++) 
                      {
                          var cityOption = {
                              "text" : "City " + i,
                              "value" : "City " + i
                          };
                          refreshDataSource.push(cityOption);
                      }
                 // Change ShipCountry item options here.
  
                      var gridObj = $("#FlatGrid").data("ejGrid");
                      for (var i = 0; i < gridObj.model.columns.length; i++)
                      {
                          if (gridObj.model.columns[i].field == "ShipCountry")
                          {
  
                              gridObj.model.columns[i].dataSource = refreshDataSource;
                              gridObj.columns(gridObj.model.columns[i],"update")
                              break;
                          }
                      }
                      }
})
</script>
 
 

 

Output Screenshot:

A screenshot of a computer

Description automatically generated

Figure 1 Bound the child grid data source dynamically

 

 

Conclusion

I hope you enjoyed learning about how to change a column's data source dynamically in JS Grid.

You can refer to our JavaScript Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our JavaScript Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied