2011-01-13 115 views
0

我有我的主窗体上一个TreeView如何将一个子节点添加到动态添加的子节点

我从我的代码到主窗体如下

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

使用这个代替:

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(...); 
      } 
    } 
} 
+0

好吧,但我如何检查并追加cnt如果节点存在 – Dotnet 2011-01-13 09:16:47

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

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