Friday 28 January 2022

DevExpress DataGrid - Add columns dynamically

This example demonstrates the DataGrid UI component communicating with a Web API service and allows to add columns dynamically.

  1. Create a CustomStore
  2. Make a call to API controller
  3. Process the controller response 
  4. Add columns dynamically in "onLoaded"


var dataGrid;
var responseData;
var col = new Array();

let customDataSource = new DevExpress.data.CustomStore({
key: "ID",
load: function (loadOptions) {
var deferred = $.Deferred();
$.ajax({
url: "/DataWorkbench/GetClientModel",
method: "GET"
})
.done(function (response) {
responseData = response;
deferred.resolve(JSON.parse(response.data), {
totalCount: response.totalCount
})
})
.fail(function (e) {
deferred.reject("Insertion failed");
});
return deferred.promise();
},
onLoaded: function (result) {

for (let i = 0; i < responseData.columns.length; i++) {
dataGrid.addColumn(responseData.columns[i]);
}
}
});



$(function () {

$("#gridContainer").dxDataGrid({
dataSource: customDataSource,
remoteOperations: true,
showBorders: true,
editing: {
mode: 'cell',
allowUpdating: true,
allowAdding: true,
allowDeleting: true,
},
customizeColumns: function (columns) {
columns[0].visible = false;

},
columns:[]
})

dataGrid = $("#gridContainer").dxDataGrid("instance");
});