C# Winforms treeview auto sort crashes my app

10 hours ago 3
ARTICLE AD BOX

I'm new to C# and I have created a winform app with a TreeView.

I have turned on sorting with this:

private void Form1_Load(object sender, EventArgs e) { TreeView1.Sorted = true; // enabled auto sort here }

Now when I create new nodes, the treeview is automatically sorted.

My problem occurs when I allow the user to rename a node from a context menu item I created. The treeview does not automatically re-sort.

In the event handler for my context menu item, I added TreeViewDecks.Sort();:

private void renameToolStripMenuItem_Click(object sender, EventArgs e) { if (TreeView1.SelectedNode != null) { TreeView1.SelectedNode.BeginEdit(); TreeView1.Sort(); // tried to call sort here stopped the edit } }

But that stops me from actually editing the label it just sorts the tree. I removed this and I tried changing the event handler TreeView1_AfterLabelEdit(...) by adding TreeViewDecks.Sort(); to the end of the method:

private void treeView1_AfterLabelEdit(object sender, System.Windows.Forms.NodeLabelEditEventArgs e) { if (e.Label != null) { if (e.Label.Length > 0) { if (e.Label.IndexOfAny(new char[]{'@', '.', ',', '!'}) == -1) { // Stop editing without canceling the label change. e.Node.EndEdit(false); } else { /* Cancel the label edit action, inform the user, and place the node in edit mode again. */ e.CancelEdit = true; MessageBox.Show("Invalid tree node label.\n" + "The invalid characters are: '@','.', ',', '!'", "Node Label Edit"); e.Node.BeginEdit(); } } else { /* Cancel the label edit action, inform the user, and place the node in edit mode again. */ e.CancelEdit = true; MessageBox.Show("Invalid tree node label.\nThe label cannot be blank", "Node Label Edit"); e.Node.BeginEdit(); } } TreeView1.Sorted = true; // tried to call sort here crashed app }

But this causes my app to crash.

MSDN TreeView.Sorted property states:

When Sorted is set to true, the TreeNode objects are sorted in alphabetical order by their Text property values. You should always use BeginUpdate and EndUpdate to maintain performance when you add a large quantity of items to a sorted TreeView. When the text of an existing node is changed, you must call Sort to resort the items.

I am trying to do what it says in the last sentence but it doesn't say when or where to call TreeView1.Sort();. I have tried to do this in my context menu event handler, and in the AfterLabelEdit handler.

Read Entire Article