Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :

Windows Forms TreeView and Sorting

Mitch Milam Profile Picture Mitch Milam

I ran into a very interesting issue last night while finishing up the user interface for my JavaScript conversion tool.

I wanted to sort TreeView so that all of the Entities and their attributes were sorted alphabetically.  Secondarily, I also wanted to put the OnLoad and OnSave events for the Entity itself at the top of the list of attributes ( since attributes only have an OnChange event ).  The desired outcome would look something like this:

image

There are several techniques that I could have used but I went with the simple approach of just moving the OnLoad and OnSave nodes after the list was sorted.  The code looks something like this:

TreeNode parentNode = workNode.Parent;
parentNode.Nodes.Remove(workNode);
parentNode.Nodes.Insert(position, workNode);

Except for the simple fact that I couldn’t for the life of me make it work.  It kept sorting the list alphabetically – which made no sense at all.

After more than a little digging, I took a shot in the dark and came up a viable solution.

 

The Problem

After I have built my TreeView, I sort the Nodes using the Sort method, like this:

treeView.Sort();

It turns out that there is a hidden property of TreeView called Sorted, which is a boolean value.  When this property is true, it will automatically sort the nodes of your TreeView each time nodes are modified.

And this Sorted is evidentially turn ON when you execute Sort.

This means that no matter how I moved nodes around my TreeView, they would always end up back in their original, sorted, location.

 

The Solution

This is very odd, but the following code will actually allow me to Sort AND move things around the TreeView:


treeView.Sort();
treeView.Sorted = false;

 

 

By setting Sorted to false, I was able to once again manipulate the TreeView nodes as I wished.

I hope this saves you some time.


This was originally posted here.

Comments

*This post is locked for comments