2013-09-26 55 views
0

我有以下功能通過樹形搜索:無法使用新的節點從樹視圖收集現有節點在C#

public static TreeNode FindAllNamesInTreeView(TreeView treeView, String name, int StartNode = -1, bool Searchilds = true) 
{ 
    TreeNode newNode = new TreeNode("SRes"); 
    newNode.Nodes.Add("Test"); 

    // check if we have a treeview 
    if (treeView == null) 
     return null; 

    // iterate through the treeview's root nodes 
    for (int i = 0; i < treeView.Nodes.Count; i++) 
    { 
     // for each root node try to find the node with the name we want 
     TreeNode foundNode = FindNameInTreeView(treeView.Nodes[i], name, StartNode, Searchilds); 

     // if we found the node, return it 
     if (foundNode != null) 
     if (TheIndexOf(foundNode) > StartNode) 
      newNode.Nodes.Add(foundNode); //Error here! 
    } 

    // no node found 
    return newNode; 
} 

上執行的newNode.Add(foundNode);我有以下例外

「類型的第一次機會異常‘System.ArgumentException’發生在System.Windows.Forms.dll中」

有誰告訴我,什麼是錯的或者我怎麼能收集添加所有找到的節點都在這裏?

回答

0

您不能將相同的節點添加到兩棵樹。因此,如果找到一個,並嘗試將其添加到newNode,則會得到一個ArgumentException

取而代之的是使用TreeNode,我建議改爲返回List<TreeNode>

+0

我想找到所有節點的集合。 將來我想遍歷它們來實現FindNext函數。 – user2819065

+0

找到決定 - 我將使用列表來存儲找到的元素: – user2819065