I have a TreeView and a Buttton on a blank Form. I add three nodes to the TreeView with text "a", "b" and "c" respectively. The TreeView has a TreeViewNodeSorter as shown below which sorts based on node text.
When the button is clicked a new node with text "aa" is added to the TreeView. If Add is called to add the node, then the sort order of the nodes is now "a", "aa", "b", "c" - as I would expect.
If AddRange is called to add the node, the order is "a", "b", "aa", "c". What is the reason for this difference?
public partial class Form1 : Form
{
TreeView treeView = null;
public Form1()
{
InitializeComponent();
treeView = new TreeView();
treeView.TreeViewNodeSorter = new TreeNodeComparer();
treeView.Nodes.Add("a");
treeView.Nodes.Add("b");
treeView.Nodes.Add("c");
Controls.Add(treeView);
Button button = new Button();
button.Text = "Add";
button.Location = new Point(treeView.Location.X, treeView.Location.Y + treeView.Height + 10);
button.Click += button_Click;
Controls.Add(button);
}
void button_Click(object sender, EventArgs e)
{
TreeNode node = new TreeNode();
node.Text = "aa";
//treeView.Nodes.Add(node);
treeView.Nodes.AddRange(new TreeNode[] { node });
}
}
public class TreeNodeComparer : IComparer
{
public int Compare(object x, object y)
{
TreeNode xNode = x as TreeNode;
TreeNode yNode = y as TreeNode;
if (xNode == null || yNode == null)
{
return 0;
}
if (xNode == null)
{
return -1;
}
if (yNode == null)
{
return 1;
}
return xNode.Text.CompareTo(yNode.Text);
}
}
There is an article here that explains things pretty well:
http://geekswithblogs.net/sdorman/archive/2007/09/21/Add-vs.-AddRange.aspx
Basically .AddRange() is the bulk performance version and strives to make things quick. You can call .Sort() on the TreeView afterwards to sort the tree as it should be. (or change the .TreeViewNodeSorter property as mentioned in the article)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With