在c#中动态地将子项添加到treenode

我想动态地将一些子节点添加到TreeView中的根节点.我有一些字符串数组,如{“john”,“sean”,“edwin”},但它可以更大或更小.

我有一个这样的根:

//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;

而我正试图用我的孩子们的名字这样做:

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

但显然它不起作用.
提示:我的子阵列中有多少元素!

编辑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没有任何补充.

您需要将子节点附加到父节点,这是一个示例:

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);
   }
}
相关文章
相关标签/搜索