在 C# 中动态添加子节点到树节点 [英] Adding childs to a treenode dynamically in c#
本文介绍了在 C# 中动态添加子节点到树节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态地将一些子节点添加到我的 TreeView
中的根节点.我有一个字符串 Array
的一些名字,比如 {"john", "sean", "edwin"}
但它可以更大或更小.
I want to dynamically add some child nodes to a root node in my TreeView
. I have a string Array
of some names like {"john", "sean", "edwin"}
but it can be bigger or smaller.
我有一个这样的根:
//Main Node (root)
string newNodeText = "Family 1"
TreeNode mainNode = new TreeNode(newNodeText, new TreeNode[] { /*HOW TO ADD DYNAMIC CHILDREN FROM ARRAY HERE?!?*/ });
mainNode.Name = "root";
mainNode.Tag = "Family 1;
我正在尝试用我的孩子名字数组来做这样的事情:
and I am trying to do like this with my array of children's names:
foreach (string item in xml.GetTestNames()) //xml.GetTestNames will return a string array of childs
{
TreeNode child = new TreeNode();
child.Name = item;
child.Text = item;
child.Tag = "Child";
child.NodeFont = new Font(listView1.Font, FontStyle.Regular);
}
但显然它不起作用.提示:我的子数组中有元素数量!!!!
But obviously it is not working. HINT: I have the number of elements in my children array!!!!
编辑 1:
我正在尝试:
//Make childs
TreeNode[] tree = new TreeNode[xml.GetTestsNumber()];
int i = 0;
foreach (string item in xml.GetTestNames())
{
textBox1.AppendText(item);
tree[i].Name = item;
tree[i].Text = item;
tree[i].Tag = "Child";
tree[i].NodeFont = new Font(listView1.Font, FontStyle.Regular);
i++;
}
//Main Node (root)
string newNodeText = xml.FileInfo("fileDeviceName") + " [" + fileName + "]"; //Text of a root node will have name of device also
TreeNode mainNode = new TreeNode(newNodeText, tree);
mainNode.Name = "root";
mainNode.Tag = pathToFile;
//Add the main node and its child to treeView
treeViewFiles.Nodes.AddRange(new TreeNode[] { mainNode });
但这不会给我的 treeView 添加任何东西.
But this will add nothing to my treeView.
推荐答案
需要将子节点追加到父节点,示例如下:
You need to append the child node to the parent, here's an example:
TreeView myTreeView = new TreeView();
myTreeView.Nodes.Clear();
foreach (string parentText in xml.parent)
{
TreeNode parent = new TreeNode();
parent.Text = parentText;
myTreeView.Nodes.Add(treeNodeDivisions);
foreach (string childText in xml.child)
{
TreeNode child = new TreeNode();
child.Text = childText;
parent.Nodes.Add(child);
}
}
这篇关于在 C# 中动态添加子节点到树节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文