【问题标题】:Override count in treeview nodes c#覆盖树视图节点中的计数c#
【发布时间】:2013-10-08 23:33:40
【问题描述】:

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

例如:

这就是我的树视图的样子

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

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

【问题讨论】:

    标签: c# count treeview overriding


    【解决方案1】:

    写一个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);
                }
            }
         }
    

    【讨论】:

    • 如果我想要更具体的东西,比如我想计算文件夹中的值怎么办?如果 treeview.CountByText("Value") 我认为它会给我 3 但实际上是 2 基于上面的示例。
    • @overshadow 我添加了更多细节
    • @overshadow 如果你想要 2,而不是 3 基于只有 2 个唯一父级的值,那么只需修改方法中的逻辑以反映这一点。或者修改扩展方法以接受 Treenode 参数而不是树视图。
    • 谢谢@Jaycee,那我怎么称呼它?我可以这样称呼它 treeview1.Nodes["Root"].Nodes["Folder"].CountByText("Value") 吗?
    • @overshadow 如果您将参数类型更改为 TreeNode,则可以。
    【解决方案2】:

    这是我根据@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;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 2012-02-10
      • 1970-01-01
      • 2016-02-16
      相关资源
      最近更新 更多