[Download Code]
The DataGridHelper.aspx page demonstrates the use of DataGridHelper control with custom columns. A live demo can be accessed at http://www.dotneteer.com/projects/DataGridHelper/v3/DataGridHelperTest.aspx.
The custom columns are created and added to the DataGrid in the page_event as shown below:
private void DataGridHelperTest_Init(object sender, System.EventArgs e)
{
DropDownColumn ddcSupplier = new DropDownColumn();
ddcSupplier.DataField = "CompanyName";
ddcSupplier.DataValueField = "SupplierID";
ddcSupplier.HeaderText = "Supplier";
ddcSupplier.SortExpression = "CompanyName";
ddcSupplier.LoadDropDownList +=new LoadDropDownListEventHandler(ddcSupplier_LoadDropDownList);
dataGridProducts.Columns.AddAt(4,ddcSupplier);
DropDownColumn ddcCategory = new DropDownColumn();
ddcCategory.DataField = "CategoryName";
ddcCategory.DataValueField = "CategoryID";
ddcCategory.HeaderText = "Category";
ddcCategory.SortExpression = "CategoryName";
ddcCategory.LoadDropDownList +=new LoadDropDownListEventHandler(ddcCategory_LoadDropDownList);
dataGridProducts.Columns.AddAt(5,ddcCategory);
CheckBoxColumn cbcDiscontinued = new CheckBoxColumn();
cbcDiscontinued.DataField = "Discontinued";
cbcDiscontinued.HeaderText = "Discontinued";
cbcDiscontinued.SortExpression = "Discontinued";
dataGridProducts.Columns.AddAt(11,cbcDiscontinued);
}
Note that it is possible to add the custom columns declaratively using tags. However, that would break the design-time behavior of the DataGrid control because it does not recognize the custom columns for the two DropDownColumn classes. Note that we also attached event handlers to the LoadDropDownList event of the DropDownColumn class. Since the two event handlers are nearly identical, we only show one below:
private void ddcCategory_LoadDropDownList(object Sender, LoadDropDownListEventArgs e)
{
DropDownList ddl = e.DropDownList;
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
SqlCommand cmd = new SqlCommand("select CategoryID, CategoryName from Categories",sqlConnection);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
ddl.DataTextField = "CategoryName";
ddl.DataValueField = "CategoryID";
ddl.DataSource = dr;
ddl.DataBind();
}
In the next section, we conclude this article.