4

我在树视图控件方面遇到问题。我对 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);

        }
    }
4

1 回答 1

1

我假设,根据代码,您正在使用 WinForms,所以我的回答将基于该假设。 ThreeNodeobject 具有Tag类型 object 的属性(与 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);

    }
}

当你想提取 的 ID 时TreeNode,只需像这样使用它(假设 ID 是 type int):

int ID = (int)tn.Tag;
于 2013-03-19T01:03:29.047 回答