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

I presume that, according to the code, you are working in WinForms so my answer will be based on that presumption. ThreeNode object has the Tag property (like any Control class in WinForms) of type object in which you can store whatever you want but you should be careful to cast it back into type when you want to use it later. So you could change your code like this:

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);

    }
}

and when you want to extract the ID of the TreeNode, just use it like this (presuming that ID is of type int):

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