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.
I have a root like this:
//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!!!!
EDIT 1:
I am trying to do:
//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 });
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);
}
}
I think the problem is that you do not inform the mainNode that child is its children, something like: mainNode.Children.Add(child) (in the for block). You just create the child node, but you don't do anything with it for it to have any relation with the TreeView or with the mainNode.
精彩评论