Quantcast
Channel: Windows Forms General forum
Viewing all articles
Browse latest Browse all 12583

Winform Treeview.Sort() does not work properly when it has a user defined TreeViewNodeSorter.

$
0
0

I found Winform Treeview.Sort() does not work properly when it has a user defined TreeViewNodeSorter.

Below is the screenshot of a simple winform application.

Treeview nodes order with TreeViewNodeSorter = null

Here is the source code:

namespace TreeViewSortTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //treeView1.TreeViewNodeSorter = new MySorter();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            treeView1.Sort();
        }

        private class MySorter : IComparer
        {
            public int Compare(object x, object y)
            {
                return 0;
            }
        }
    }
}

No matter how many times I hit the sort button, the nodes order keep unchanged. it is ascending. This is the default sorter's behavior (TreeViewNodeSorter == null)

But if I uncomment this line :

//treeView1.TreeViewNodeSorter = new MySorter();

whenever I click the sort button, the nodes order changes - ascending and descending alternatively.

Nodes in wrong order

In my real application, the Compare() is much more complicated. Here I purposely return 0 in method Compare() in MySorter class, in order to maintain the original nodes order in the treeview. I want to keep them unchanged when I hit the sort button, same as what the default sorter behaves (when TreeViewNodeSorter == null).

My question is - If the TreeView has a user defined TreeViewNodeSorter, and I'd like to keep the order of some nodes unchanged, what should I do? looks like returning 0 in Compare() does not work.


Viewing all articles
Browse latest Browse all 12583

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>