1

I have a TreeView on my winform which uses a subclass of TreeNode with some additional variables I want to store against each node. Users can delete nodes from my tree using a context menu.

What I'd like to be able to do is extend the Remove method for TreeNode so that I do some extra processing in there before the node is removed. Is there a way to do this?

To clarify...

Is there a way to extend the existing Remove method for TreeNode so that code can be executed before it's actually does the remove?

Cheers,

EDIT: Im actually assuming that the way i'll have to do this is extend the class with a new method which calls this.Remove() instead?

EDIT 2: This is what I ended up doing. Is it the best way...

public partial class CustomTreeNode : TreeNode
{
    // My custom TreeNode vars
    public int UID;
    public int ParentUID;

    public CustomTreeNode(string nodeName) : base(nodeName)
    {
        // Set the tree node here
    }

    public void RemoveIt()
    {
        // Custom stuff
        System.Console.WriteLine("Deleted");

        base.Remove();
    } 

}
Simon
  • 8,981
  • 2
  • 26
  • 32

2 Answers2

1

Try this in your sub-class

public new void Remove() 
{ 
    //do your custom stuff

    base.Remove();  // calls the TreeNode Remove method
}

Edit: added new removed override

Just be aware that any time you reference sub-class objects as a TreeNode then your custom Remove method will not be called Difference between new and override

You could also name the function something else like this:

public void SuperRemove() 
{ 
    //do your custom stuff

    base.Remove();  // calls the TreeNode Remove method
}
Community
  • 1
  • 1
Joel
  • 196
  • 1
  • 6
  • When I try that, I get "cannot override inherited member 'System.Windows.Forms.TreeNode.Remove()' because it is not marked virtual, abstract or override. – Simon Apr 24 '12 at 16:11
0

You are deleting node from context menu. Why not to add some extra processing to MenuItem_Click event handler? You can do anything there before invoking Remove of node.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • Mostly because this action will happen a lot in my tree and I wanted the object itself to handle it's deletion from SQL without having to write all that code for every instance of .Remove() – Simon Apr 24 '12 at 17:23