Category / Section
How to add column dynamically to SfDataGrid when an ItemsSource is DataTable
1 min read
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;