【问题标题】:Adding nodes to a specific parent node in a treeView (c#)将节点添加到树视图中的特定父节点(c#)
【发布时间】:2012-02-10 07:03:20
【问题描述】:

我目前正在向 treeView 中的父节点添加各种值,虽然我不知道如何添加到树下的特定节点,目前它只是添加到“选定节点”

 using (var reader = File.OpenText("Configuration.ini"))
            {
                List<string> hostnames = ParseExternalHosts(reader).ToList();
                foreach (string s in hostnames)
                {
                    TreeNode newNode = new TreeNode(s);
                    hostView.SelectedNode.Nodes.Add(newNode);
                }

【问题讨论】:

  • 你想做什么?请举例说明您的期望。

标签: c# .net windows


【解决方案1】:

您可以使用TreeView.Nodes.Find() 方法在TreeView 控件中搜索特定节点。

下面的示例首先将两个节点添加到 TreeView 控件,为每个节点指定一个名称 (=key)。

const string nodeKey = "hostNode";

TreeNode tn1 = new TreeNode("My Node");
tn1.Name = nodeKey; // This is the name (=key) for the node.

TreeNode tn2 = new TreeNode("My Node2");
tn2.Name = "otherKey"; // This is the key for node 2.

treeView1.Nodes.Add(tn1); // Add node1.
treeView1.Nodes.Add(tn2); // Add node2.

然后,要在上面创建的树视图中搜索 node1 (tn1),请使用以下代码:

// Find node by name (=key). Use the key specified above for tn1.
// If key is not unique you will get more than one node here.
TreeNode[] found = treeView1.Nodes.Find(nodeKey, true);

// Do something with the found node - e.g. add just another node to the found node.
TreeNode newChild = new TreeNode("A Child");
newChild.Name = "newChild";

found[0].Nodes.Add(newChild);

希望,这会有所帮助。

【讨论】:

    猜你喜欢
    • 2015-03-20
    • 2010-11-26
    • 2012-04-15
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2012-04-05
    • 2011-09-28
    • 2012-07-02
    相关资源
    最近更新 更多