覆盖树视图节点中的计数c#

时间:2013-10-08 23:33:41

标签: c# count treeview override

我想以适当的方式覆盖树视图节点中的计数,以便按特定文本或名称获取节点数。有可能这样做吗?提前谢谢。

例如:

这就是我的树视图的样子

enter image description here

在这种情况下,如果我使用treeView1.Nodes [0] .Nodes.Count,我将获得3,这是Root中的节点数。

我想要这样的东西,treeView1.Nodes [0] .Nodes.CountByText(“Folder”)将返回2,Root节点中存在确切的节点数(Text =“Folder”)

2 个答案:

答案 0 :(得分: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);
            }
        }
     }

答案 1 :(得分: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;
    }

}