如何将子节点添加到动态添加的子节点

时间:2011-01-13 09:03:02

标签: c# winforms treeview .net-2.0

我正在主表单上查看树视图

我的代码从from到main格式如下

 Buttonclick

StrNode = string.Empty;
StrNode = "Batch" + Append.Batchcnt.ToString() + "(" + strSelectedClassCode + ")";
frmmain.loadFromForm(StrNode, true, strSelectedClassCode);

在我的主表单上,我的代码如下

public void loadFromForm(string strNode, bool bResult, string strStandardClsCode)
    {
        if (Append.oldbatchcontrol != strNode)
        {
            if (tvwACH.SelectedNode.Text == "FileHeader")
            {
                tvwACH.SelectedNode.Nodes.Add(strNode);
            }
            if (tvwACH.SelectedNode.Text == "BatchHeader")
            {
                tvwACH.SelectedNode.Nodes.Add(strNode);// After this i have to add another node as a child to that added node and also if a node with particular name exists i would like to write the text with a count value appended
            }
  }
        }

这样我的树视图应该如下

ACH
|->Some.txt
  |->Fileheader
    |->BatchHeader
       |->Batch1
          |->Entry1
          |->Entry2 and so on // These two should be added dynamically after that Batch1

2 个答案:

答案 0 :(得分:2)

请改用:

public void loadFromForm(string strNode, bool bResult, string strStandardClsCode)
    {
        if (Append.oldbatchcontrol != strNode)
        {
            if (tvwACH.SelectedNode.Text == "FileHeader")
            {
                tvwACH.SelectedNode.Nodes.Add(strNode);
            }
            if (tvwACH.SelectedNode.Text == "BatchHeader")
            {
                TreeNode node = tvwACH.SelectedNode.Nodes.Add(strNode,strNode);// After this i have to add another node as a child to that added node and also if a node with particular name exists i would like to write the text with a count value appended
                node.Nodes.Add(...);
            }
  }
}

答案 1 :(得分:1)

您通常需要一个递归函数来构建树。例如:

private void AddNode(NodeParent, Data)
{
    Node oNode;

    //Check if this is the first node
    if (NodeParent ==null)
    {
         oNode = new Node(Data.Name);
    }

    //Step though each child item in the data
    foreach(DataItem in Data)
    {
        //Add the node
         this.AddNode(oNode, DataItem);
    }

    oNode.Nodes.Add(new Node(Data));
}

此代码是一个粗略的指南,但它应该给你一个想法。