Editing Labels in a Sorted TreeView

In my previous post we've been dealing with TreeView drag&drop. One other functionality that is almost mandatory for TreeView is renaming a node. While basic code is quite straight forward, there are few tricks in order to get better-than-default behavior.

First order of business is BeforeLabelEdit event. There we define which nodes will have fixed name. In our case, we will not allow editing of folder names:

e.CancelEdit = (e.Node.ImageIndex == 0); //don't allow editing folders

In AfterLabel event we handle everything else. We want new text without spaces on either end and no duplicates are allowed. It complicates code a bit but not by much. Probably only non obvious thing is actual sorting. Here we just "schedule" it after event handler is done with processing:

if (e.Label == null) { return; } //no change was made
e.CancelEdit = true; //we will handle changes manually
string newText = e.Label.Trim(); //no spaces

var nodes = (e.Node.Parent == null) ? tree.Nodes : e.Node.Parent.Nodes;
foreach (TreeNode node in nodes) {
if ((node != e.Node) && string.Equals(newText, node.Text, StringComparison.Ordinal)) {
return; //duplicate name

e.Node.Text = newText; //rename manually

tree.BeginInvoke(new Action<TreeNode>(delegate(TreeNode node) { //sort again
tree.SelectedNode = node;
}), e.Node);

Full sample can be downloaded here.

PS: In sample code you will see that I use ImageIndex==0 to determine whether node is of folder type. In real program you would probably go with sub-classing TreeNode.

Leave a Reply

Your email address will not be published. Required fields are marked *