How do I override TreeNodeCollection.Add(TreeNode)?

大城市里の小女人 提交于 2019-12-06 06:03:21

Add method belongs to TreeNodeCollection class. If you like to have new Add methods with new signatures:

  • Naturally you may think about deriving from TreeNodeCollection and defining new methods and derive from TreeView and replace its TreeNodeCollection with your new custom node collection. But don't try this solution. TreeNodeCollection doesn't have a public constructor. So I'd suggest creating Extension Methods.

  • The other solution that you may think about it is deriving from TreeView and adding new Add methods to the derived TreeView.

Example - Extension Methods

Create a new code file and copy the following code and paste it in the code file:

namespace MyExtensions
{
    using System.Windows.Forms;
    public static class TreeNodeCollectionExtensions
    {
        //Just an example of a new signature, use the signature that you need instead:
        public static TreeNode Add(this TreeNodeCollection nodes, string text, int tag)
        {
            var node = nodes.Add(text);
            node.Tag = tag;
            return node;
        }
    }
}

Then in the class which you are going to use the new Add method, first add the using statement:

using MyExtensions;

Then use it like a normal method:

treeView1.Nodes.Add("One", 1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!