我遇到了有关树视图控件的问题。我是C#的新手,并坚持如何将ID添加到相应的树节点。我不确定这行代码是否包含ID,如果没有,那么我应该包括什么。我想获取所选节点的ID。我如何继续请告诉我。我的代码如下 -
提前致谢。
private void PopulateTreeView()
{
treeDepartments.Nodes.Clear();
String strConn = "Server =server;Database =DB;Integrated Security = True;";
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("Select * from tSubDepartments", conn);
SqlDataAdapter daCategories = new SqlDataAdapter("Select * from tDepartments", conn);
da.Fill(ds, "tSubDepartments");
daCategories.Fill(ds, "tDepartments");
ds.Relations.Add("Dept_SubDept", ds.Tables["tDepartments"].Columns["dpCode"], ds.Tables["tSubDepartments"].Columns["dpCode"]);
foreach (DataRow dr in ds.Tables["tDepartments"].Rows)
{
TreeNode tn = new TreeNode(dr["dpName"].ToString());
foreach (DataRow drChild in dr.GetChildRows("Dept_SubDept"))
{
tn.Nodes.Add(drChild["sdName"].ToString());
}
treeDepartments.Nodes.Add(tn);
}
}
答案 0 :(得分:1)
我认为,根据代码,你在WinForms工作,所以我的答案将基于这个假设。
ThreeNode
对象具有类型为object的Tag
属性(类似于WinForms中的任何Control类),您可以在其中存储您想要的任何内容但是当您想要使用它时应该小心地将其强制转换为类型后来。所以你可以改变你的代码:
private void PopulateTreeView()
{
treeDepartments.Nodes.Clear();
String strConn = "Server =server;Database =DB;Integrated Security = True;";
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("Select * from tSubDepartments", conn);
SqlDataAdapter daCategories = new SqlDataAdapter("Select * from tDepartments", conn);
da.Fill(ds, "tSubDepartments");
daCategories.Fill(ds, "tDepartments");
ds.Relations.Add("Dept_SubDept", ds.Tables["tDepartments"].Columns["dpCode"], ds.Tables["tSubDepartments"].Columns["dpCode"]);
foreach (DataRow dr in ds.Tables["tDepartments"].Rows)
{
TreeNode tn = new TreeNode(dr["dpName"].ToString());
tn.Tag = dr["dpID"]; //put the ID into the Tag property of the node
foreach (DataRow drChild in dr.GetChildRows("Dept_SubDept"))
{
TreeNode childTn = new TreeNode(drChild["sdName"].ToString());
childTn.Tag = drChild["sdID"];
tn.Nodes.Add(childTn);
}
treeDepartments.Nodes.Add(tn);
}
}
当您想要提取TreeNode
的ID时,只需像这样使用它(假设ID类型为int
):
int ID = (int)tn.Tag;