Treeview节点标签奇怪地创建

时间:2014-05-05 08:37:14

标签: c# treeview treenode

我已经通过动态创建的节点/子节点获得了树视图控件。当用户单击特定节点时,应使用某些相关节点信息/设置更新表格显示。为了跟踪点击哪个节点,我在节点创建运行时添加了一个自定义标记(一个名为' NodeTag'包含两个字段的类)。我订阅了AfterSelect' AfterSelect'树视图控件的事件,我想检查SelectedNode.Tag,但奇怪的是我总是得到所有选定对象的最后一个标记对象:所有节点都有NodeTag.Nodename =" GLBS&#34 ;和NodeTag.NodeNumber = 0.这是一张图片,其中“当前会话”是如果选中,则所选节点文本正确但标签不正确。

Current Session selected as node

以下是代码:

TreeNode SessionNode = new TreeNode("Current Session");
            //Add Tag object to the new node
            NodeTag nt = new NodeTag();
            nt.NodeName = "SESS";
            nt.NodeNumber = 0;
            SessionNode.Tag = (object) nt;
            tv_project.Nodes.Add(SessionNode);


            MainProject.ProjectNode = new TreeNode("Project - " + e.ProjName + " - " + e.ProjOwner);
            //Add Tag object to the new node
            nt.NodeName = "PROJ";
            nt.NodeNumber = 0;
            MainProject.ProjectNode.Tag = (object) nt;
            SessionNode.Nodes.Add(MainProject.ProjectNode);


            TreeNode SettingsNode = new TreeNode("Global Settings");
            //Add Tag object to the new node
            nt.NodeName = "GLBS";
            nt.NodeNumber = 0;
            SettingsNode.Tag = (object) nt;
            SettingsNode.ForeColor = Color.Red;
            MainProject.ProjectNode.Nodes.Add(SettingsNode);

1 个答案:

答案 0 :(得分:0)

我有解决方案!

您刚刚第一次创建NodeTag的实例,然后您只需修改它 您必须为每个节点创建单独的nt

TreeNode SessionNode = new TreeNode("Current Session");
        //Add Tag object to the new node
        NodeTag nt = new NodeTag();
        nt.NodeName = "SESS";
        nt.NodeNumber = 0;
        SessionNode.Tag = (object) nt;
        tv_project.Nodes.Add(SessionNode);


        MainProject.ProjectNode = new TreeNode("Project - " + e.ProjName + " - " + e.ProjOwner);
        //Add Tag object to the new node
        NodeTag nt1 = new NodeTag();
        nt1.NodeName = "PROJ";
        nt1.NodeNumber = 0;
        MainProject.ProjectNode.Tag = (object) nt1;
        SessionNode.Nodes.Add(MainProject.ProjectNode);


        TreeNode SettingsNode = new TreeNode("Global Settings");
        //Add Tag object to the new node
        NodeTag nt2 = new NodeTag();
        nt2.NodeName = "GLBS";
        nt2.NodeNumber = 0;
        SettingsNode.Tag = (object) nt2;
        SettingsNode.ForeColor = Color.Red;
        MainProject.ProjectNode.Nodes.Add(SettingsNode);