tags:

views:

694

answers:

3

I want to write a custom class in which whenevr I add a node to treeview it should call an event. so that I can run it recursively.

A: 

Delegates maybe? Do you want to raise the event or create a new one?

BBetances
I want to raise the Event I have inherited my custome class from Treeview
+1  A: 

I've rarely used TreeView, but at a glance this is my first impression. Since TreeViewCollection cannot be inherited from, you may have to create a separate method on your new class that will perform the actual adding to the Nodes collection. This will allow you to tie in an event. Something like this in your inherited class:

public event EventHandler NodeAdded;

public void AddNode(TreeViewNode node)
{
    Nodes.Add(node);
    if (NodeAdded != null)
    {
        NodeAdded(this, EventArgs.Empty);
    }
}

You could then create a custom EventArgs class and include any information you may want to use.

Tony Basallo
There is no TreeViewCollection class that I am aware of, sealed or otherwise. There is a TreeNodeCollection, which is not sealed.
Chris Ammerman
That's correct, TreeNodeCollection. However, it cannot be inherited from, which I mistakingly assumed was because it was sealed (should have kept reading). My original answer would have been to create an inherited collection class. (edited my answer)
Tony Basallo
Ah, I see now. According to Reflector, TreeNodeCollection has one, internal constructor. So MS wants to be able to inherit from it, but prevents anyone else from doing so.
Chris Ammerman
+1  A: 

Unfortunately, since TreeNodeCollection is in fact a tree, I think you're going to be stuck needing to implement your own tree view control essentially from scratch, with a custom tree data structure with events, or finding a third-party or open source one to use.

If it were a simple collection, I'd say just wrap a framework TreeView control in a custom user control, and hide the Nodes property, exposing only the accessors and mutators you want. Then you could just fire your control's events before and/or after passing the calls through to the underlying TreeView control. However, this would only give you events on the first layer of nodes.

It's easy to make a List or Dictionary class with mutator events, because you can just wrap them like that. But trees are royal pain to have to implement, especially if you're going to distribute or sell the code that uses it. And unfortunately, we get essentially no help with them from the .NET framework. Because of all the complexities of implementing a tree structure, I would strongly recommend trying to find a pre-made solution, either third-party or open source.

Chris Ammerman