在TreeView(c#)中将节点添加到特定父节点

3

我目前正在向树形视图中的父节点添加各种值,但我无法找出如何添加到树下特定的节点,目前它只是添加到“选定节点”。

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

你想做什么?给我们一个你期望的例子。 - ken2k
1个回答

6
你可以使用 TreeView.Nodes.Find() 方法在 TreeView 控件中搜索特定节点。
下面的示例首先向 TreeView 控件添加两个节点,并指定每个节点的名称(=键)。
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.

接下来,要在上面创建的树形视图中搜索节点1(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);

希望这能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接