C# – Getting treenode text after an edit

ctreeviewwinforms

I've got a treeview where I allow users to create new tree nodes. When they create a tree node, I automatically go into edit mode. What I am trying to do is save the name given to the tree node after the edit finishes in "AfterLabelEdit".

What I've found is that checking the label in this method returns the original label because it doesn't appear to be committed to the tree until after the method finishes.

How can I get the new label after an edit has taken place? Is there a way to force the changes to commit in this method?

Hope that makes sense!

Best Answer

The actual node text doesn't change until after the AfterLabelEvent event completes. The event passes the new label text in the e.Label property. That's the one you want.

A standard trick to deal with the balky TreeView events is to delay the action until the event is completed. Elegantly done with the Control.BeginInvoke() method:

    private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {
        this.BeginInvoke(new Action(() => afterAfterEdit(e.Node)));
    }
    private void afterAfterEdit(TreeNode node) {
        string txt = node.Text;   // Now it is updated
        // etc..
    }
Related Topic