2013-10-08 44 views
1

我想以正確的方式覆蓋樹視圖節點中的計數,以便通過特定文本或名稱獲取節點的計數。有可能這樣做?提前致謝。在treeview節點中覆蓋計數c#

例如:

這是我的樹視圖看起來像

enter image description here

在,如果我使用treeView1.Nodes [0] .Nodes.Count這種情況下,我會得到3這是根中的節點數。

我想要類似這樣的東西,treeView1.Nodes [0] .Nodes.CountByText(「Folder」)將返回我2,節點的確切數目(文本=「文件夾」)存在於根節點。

回答

2

寫一個extension method

public static int CountByText(this TreeView view, string text) 
{ 
    //logic to iterate through nodes and do count 
    return count; 
} 

你可以再做:

var count = treeview.CountByText("Folder"); 

你可以通過在TreeNodeCollection做的還,根據您的喜好。

編輯:

一些簡單的代碼來說明:

static class Class1 
    { 
     public static int CountByText(this TreeView view, string text) 
     { 
      int count = 0; 

      //logic to iterate through nodes and do count 
      foreach (TreeNode node in view.Nodes) 
      { 
       nodeList.Add(node); 
       Get(node); 
      } 
      foreach (TreeNode node in nodeList) 
      { 
       if (node.Text == text) 
       { 
        count++; 
       } 
      } 
      nodeList.Clear(); 
      return count; 
     } 

     static List<TreeNode> nodeList = new List<TreeNode>(); 
     static void Get(TreeNode node) 
     { 
      foreach (TreeNode n in node.Nodes) 
      { 
       nodeList.Add(n); 
       Get(n); 
      } 
     } 
    } 
+0

如果什麼我想要更具體的東西,比如我想計算文件夾中的值?如果treeview.CountByText(「Value」)我認爲它會給我3,但實際上是上面的例子2基地。 – overshadow

+0

@overshadow我添加了一些更詳細的信息 –

+0

@overshadow如果你想要2,而不是3基於價值只有2獨特的父母,然後簡單地修改方法內的邏輯來反映。或者修改擴展方法以接受Treenode參數而不是樹視圖。 –

1

這是由@Jaycee提供的代碼我的修改版本基礎,我希望它能幫助其他

public static class Extensions 
{ 
    public static int CountByText(this TreeNode view, string text) 
    { 
     int count = 0; 

     //logic to iterate through nodes and do count 
     foreach (TreeNode node in view.Nodes) 
     { 
      if (node.Text == text) 
      { 
       count++; 
      } 
     } 
     return count; 
    } 

}