Many of you might have come across a requirement to create a DataGrid in the code-behind. Here, I am sharing a small snippet to give you an idea on how to perform this:
Let's say, our class is Product, as shown below:
public class Product
{public int ProductID { get; set; }
public string ProductName { get; set; }
public bool IsAvailable { get; set; }
}
Next is to create DataGrid
DataGridTextColumn col1 = new DataGridTextColumn();
col1.Header = "Product ID";col1.Binding = new Binding("ProductID");
dataGrid1.Columns.Add(col1);
DataGridCheckBoxColumn col2 = new DataGridCheckBoxColumn();
col2.Header = "IsAvailable";col2.Binding = new Binding("IsAvailable");
dataGrid1.Columns.Add(col2);
DataGridTextColumn col3 = new DataGridTextColumn();
col3.Header = "ProductName";col3.Binding = new Binding("ProductName");
dataGrid1.Columns.Add(col3);
dataGrid1.Items.Add(new Product() { ProductID=1, ProductName="Product1", IsAvailable=true });
dataGrid1.Items.Add(new Product() { ProductID=2, ProductName="Product2", IsAvailable=false });dataGrid1.Items.Add(new Product() { ProductID=3, ProductName="Product3", IsAvailable=true });
dataGrid1.Items.Add(new Product() { ProductID=4, ProductName="Product4", IsAvailable=false });

sanjeet kumarPosted Jun 21, 2018, 7:24 AM
What rubbish
sumit pitrodaPosted Nov 28, 2017, 4:52 AM
How to set cell alignment in wpf datagrid?
Shweta LodhaPosted Feb 27, 2014, 11:49 AM
Good to know that it seems to be useful for you. Thanks
Sompal AryaPosted Feb 27, 2014, 4:32 AM
Thanks for sharing...