A few things to keep in mind:
- The
AfterLabelEdit event always ends the editing mode after raising it, even if you call BeginEdit in the middle of the event handler. You can use TreeView.BeginInvoke to "skip" this by running EditMode after the TreeView does its job. (NOTE: this does not create a new thread or race condition, it just delays the method for 1 message box.) There is more information about some issues with this event here (although this suggests what I consider to be the worst solution). e.Label null if the user has not made any changes, so when we “skip” with BeginInvoke, it is as if the user has not made any changes, so we also need to handle this case.- BeginInvoke is an acceptable workaround in this case, you should find it very reliable in this situation.
This works very well for me, tested with .NET 2.0:
private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { //we have to handle both the first and future edits if ((e.Label != null && e.Label.Contains("|") || (e.Label == null && e.Node.Text.Contains("|")))) { if (WantAutofix()) { e.CancelEdit = true; if(e.Label != null) e.Node.Text = e.Label.Replace('|', '_'); else e.Node.Text = e.Node.Text.Replace('|', '_'); } else { //lets the treeview finish up its OnAfterLabelEdit method treeView1.BeginInvoke(new MethodInvoker(delegate() { e.Node.BeginEdit(); })); } } } private bool WantAutofix() { return MessageBox.Show("You entered a |, you want me to AutoFix?", String.Empty, MessageBoxButtons.YesNo) == DialogResult.Yes; }
source share