2
votes

I need to fill WPF DataGrid from DataTable programmatically. List of columns is not know in design time.

Columns should be generated manually (AutoGeneratingColumn event?) based on simple template having single Label. Label.Content is column name. Now binding allowed - template can be created in XAML but everything else need to be in C#

A little bit complex approach is for rows. Data cell template should have single Label or TextBox but cell template should be set in runtime. For instance, string should be represented in cell is longer that 5 chars, then Label-based template should be used. Otherwise, TextBox template should be used. Again, templates only can be created in XAML. Filling data need to be done in C#

Here's some code to start with in order to generate data:

DataTable myTable = new DataTable(tableName);
myTable.Columns.Add(new DataColumn("id", typeof(int)));  
myTable.Columns.Add(new DataColumn("name", typeof(string)));
myTable.Rows.Add(new object[] {1, "label"});   
myTable.Rows.Add(new object[] {2, "text box"});
1

1 Answers

0
votes

You can add the columns in the datagrid programatically by defining DataGridTextColumn and set its width, header and Binding.

Here is a little example to get you the idea

DataGridTextColumn column1 = new DataGridTextColumn();
column1.Header = myTable.Columns[0].Caption;
column1.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
column1.Binding = new Binding("column1_name");

DataGridTextColumn column1 = new DataGridTextColumn();
column1.Header = myTable.Columns[1].Caption;
column1.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
column1.Binding = new Binding("column2_name");

dataGrid.Columns.Add(column1);
dataGrid.Columns.Add(column2);

Using this way you can define multiple columns in datagrid without knowing the no.of Columns at design time