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 });