在C#中动态地向树节点添加子节点

4
我希望能在我的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);
        }

但显然它并没有起作用。

提示:我已经知道了我的 children 数组中元素的数量!!!

编辑 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没有任何帮助。

2个回答

16
您需要将子节点附加到父节点,这里是一个示例:
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);
   }
}

0
我认为问题在于您没有告知mainNode,child是其子节点,类似于:mainNode.Children.Add(child)(在for循环块中)。您只是创建了子节点,但您没有对其进行任何操作,使其与TreeView或mainNode有任何关系。

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