Thursday, August 18, 2011

Dynamic data binding in datagrid in WPF

DataTable dt = new DataTable("Test");
DataColumn col1 = new DataColumn("Name", typeof(string));
DataColumn col2 = new DataColumn("Age", typeof(int));
dt.Columns.Add(col1);
dt.Columns.Add(col2);
DataRow row1 = dt.NewRow();
row1[0] = "India";
row1[1] = 880;
DataRow row2 = dt.NewRow();
row2[0] = "Srilanka";
row2[1] = 745;
dt.Rows.Add(row1);
dt.Rows.Add(row2);

foreach (DataColumn col in dt.Columns)
{
DataGridTextColumn dCol1 = new DataGridTextColumn();
Binding binding = new Binding("["+col.ColumnName+"]");
dCol1.Binding = binding;
dCol1.Header = col.ColumnName;
dataGrid1.Columns.Add(dCol1);

}



dataGrid1.ItemsSource = dt.Rows;

No comments:

Post a Comment