2011-01-13 191 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)); 
} 

此代碼是一個粗略的指南,但它應該給你一個想法。