Displaying Hierarchical Data in DropDownList
Sometimes you need to view the hierarchical data in the DropDownList. Something like the following:
Category 1
Product 1
Product 2
Category 2
Product 3
Product 10
and like that. Here is a simple code that shows the hierarchical data in the DropDownList. I am using the Northwind database.
private void BindData()
{
string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand("usp_GetProductsForCategories",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
int categoryID = Convert.ToInt32(row["CategoryID"]);
string categoryName = row["CategoryName"] as String;
ddlCategories.Items.Add(new ListItem( categoryName , categoryID.ToString()));
DataRow[] childRows = ds.Tables[1].Select("CategoryID = " + categoryID);
foreach (DataRow childRow in childRows)
{
ddlCategories.Items.Add(new ListItem( (string) childRow["ProductName"], (childRow["ProductID"].ToString())));
}
}
// bind the dropdownlist
ddlCategories.DataBind();
}