Question about sorting a treeview.

Posted on 2011-05-04
Last Modified: 2013-12-16

I have a treeview with nodes with an imageindex 0 (folder node) and 1 (file node).
How can I sort the treeview first on the folder nodes and then the file nodes.
And sort them both alfabeticly. Like Windows Explores has.

Who knows the anwer and is willing to help me?


Peter Kiers
Question by:peterkiers
    LVL 11

    Expert Comment

    LVL 11

    Accepted Solution

    If so, then you can define your own sorting using IComparer.

            public class CompareTreeNodes : IComparer
                public int Compare(object obj1, object obj2)
                    TreeNode treeNode1 = obj1 as TreeNode;
                    TreeNode treeNode2 = obj2 as TreeNode;

                    // Compare the length of the strings, returning the difference.
                    if (treeNode1.ImageIndex != treeNode2.ImageIndex)
                        return treeNode1.ImageIndex - treeNode2.ImageIndex;

                    // If they are the same length, call Compare.
                    return string.Compare(treeNode1.Text, treeNode2.Text);


    And in your code:
    treeView1.TreeViewNodeSorter = new CompareTreeNodes();

    You can read more about it here:

    Featured Post

    Top 6 Sources for Identifying Threat Actor TTPs

    Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

    Join & Write a Comment

    Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
    This video discusses moving either the default database or any database to a new volume.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now