类别动态绑定到TreeView控件
一个产品名下有几个子类产品名,如何绑定到TreeView中。
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyAdventureWorksConnectionString"].ConnectionString))
{
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataSet ds = new DataSet();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select ProductCategoryID,Name from Production.ProductCategory";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
sda.Fill(dt1);
con.Close();
cmd.CommandText = "select ProductSubcategoryID,Name,ProductCategoryID from Production.ProductSubcategory";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt2);
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
DataRelation dr = new DataRelation("treeRelation", dt1.Columns[0], dt2.Columns[2]);
ds.Relations.Add(dr);
for (int i = 0; i < dr.ParentTable.Rows.Count; i++)
{
this.TreeView1.Nodes.Add(new TreeNode(dr.ParentTable.Rows[i].ItemArray[1].ToString(), dr.ParentTable.Rows[i].ItemArray[0].ToString()));
DataRow[] dRow = dr.ParentTable.Rows[i].GetChildRows(dr);
for (int j = 0; j < dRow.Length; j++)
{
this.TreeView1.Nodes[i].ChildNodes.Add(new TreeNode(dRow[j].ItemArray[1].ToString(), dRow[j].ItemArray[0].ToString()));
}
}
}