2010-09-22 190 views
6
ROOT 
     A 
     B 
      C 
      D 
       E 
     T 
     F 
     G 
     X 

我想查找E節點的父節點(它是數字5)。然後,我將保存節點。如果數字較小5.我在Asp.net控件中使用TreeView。如何在根節點查找子節點[TreeView]

+0

@Özkan的:什麼號碼4?你想找到深度嗎? – 2010-09-22 09:10:30

+0

父母是'D',對吧? – 2010-09-22 09:13:25

+0

@Albin,是的,我想找到一個節點的深度。 – ozkank 2010-09-22 09:16:51

回答

7

我會建議使用遞歸迭代。

private TreeNode FindNode(TreeView tvSelection, string matchText) 
{ 
    foreach (TreeNode node in tvSelection.Nodes) 
    { 
     if (node.Tag.ToString() == matchText) 
     { 
      return node; 
     } 
     else 
     { 
      TreeNode nodeChild = FindChildNode (node, matchText); 
      if (nodeChild != null) return nodeChild; 
     } 
    } 
    return (TreeNode)null; 
} 

你可以利用這個邏輯判斷很多事情你節點,這種結構也允許你擴大你可以用節點和你想搜索的標準做什麼。您可以編輯我的示例以適合您自己的需求。

因此,在這個例子中,如果返回的節點的父屬性是您之後的父節點,那麼您可以傳遞E並期望返回節點E,然後簡單地返回 。

tn treenode = FindNode(myTreeview, "E") 

tn.parent是你以後的值。

1
private TreeNode GetNode(string key) 
    { 
     TreeNode n = null ; 
     n = GetNode(key, Tree.Nodes); 
     return n; 
    } 
    private TreeNode GetNode(string key,TreeNodeCollection nodes) 
    { 
     TreeNode n = null; 
     if (nodes.ContainsKey(key)) 
      n = nodes[key]; 
     else 
     { 
      foreach (TreeNode tn in nodes) 
      { 
       n = GetNode(key, tn.Nodes); 
       if (n != null) break; 
      } 
     } 

     return n; 
    } 
+1

嘗試並解釋您的代碼。 – 2013-04-04 07:10:59

1

我很好奇,因爲這被標記爲WebForm,爲什麼不提示Microsoft的FindNode方法。它從v2.0到現在(目前爲v4.5.2)兼容。

這是不是在這裏工作?

從微軟的MSDN:

使用FindNode方法來獲得從規定值路徑TreeView控件的一個節點。值路徑包含一個分隔符分隔的節點值列表,它們構成從根節點到當前節點的路徑。每個節點都將其值路徑存儲在ValuePath屬性中。 PathSeparator屬性指定用於分隔節點值的分隔符。

例子:

void Button_Click(Object sender, EventArgs e) 
{ 

    // Find the node specified by the user. 
    TreeNode node = LinksTreeView.FindNode(Server.HtmlEncode(ValuePathText.Text)); 

    if (node != null) 
    { 
    // Indicate that the node was found. 
    Message.Text = "The specified node (" + node.ValuePath + ") was found."; 
    } 
    else 
    { 
    // Indicate that the node is not in the TreeView control. 
    Message.Text = "The specified node (" + ValuePathText.Text + ") is not in this TreeView control."; 
    } 

}