Articles in this section

How to add column dynamically to SfDataGrid when an ItemsSource is DataTable

When the ItemsSource is DataTable, you can add the new column dynamically to SfDataGrid by adding SfDataGrid.Columns.

C#

sfDataGrid.AutoGenerateColumns = true;
sfDataGrid.AutoGenerateColumnsMode = AutoGenerateColumnsMode.RetainOld;
 
this.GenerateDataTable();
sfDataGrid.ItemsSource = employees;

But sorting, grouping and filtering won’t work with newly added column. To make this work, you have to reset the ItemsSource of SfDataGrid.

C#

var newColumn = string.Format("AddColumn{0}", sfDataGrid.Columns.Count);
employees.Columns.Add(newColumn, Type.GetType("System.String"));
 
Random rand = new Random();
foreach (DataRowView item in employees.DefaultView)
{
    item[newColumn] = rand.Next(10, 1000).ToString();
}
 
GridTextColumn textColumn = new GridTextColumn();
textColumn.MappingName = newColumn;
sfDataGrid.Columns.Add(textColumn);
 
//Reset ItemsSource to make sorting, filtering and grouping to work in with newly added //column when ItemsSource is DataTable
sfDataGrid.ItemsSource = null;
sfDataGrid.ItemsSource = employees.DefaultView;

 

Download sample here

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied