Reputation: 2863
I using TreeView with ShowCheckBoxes="All" in an ASP.NET 3.5 web application and for some reason the checked nodes are not returned in order. Lets say I have nodes A,B,C and I select B and C and hit the save button and when I check the CheckedNodes property of the Treeview the checked nodes are in order (B,C). But the next time when I go back to the page and select the node A the order is being returned B,C,A. What could be the reason for this behavior?
Upvotes: 3
Views: 683
Reputation: 21314
A simple routine to sort the CheckedNodes
collection will suffice as a solution to this problem. This routine (http://urenjoy.blogspot.com/2009/06/sort-checkednodes-treenodecollection-in.html) which I ran across from a search works directly by calling prior to looping through the collection. It essentially checks the text in a simple comparison and returns a new collection in order.
From the link above:
private TreeNodeCollection SortTreeNode(TreeNodeCollection nodeList)
{
for (int i = 0; i < nodeList.Count-1; i++)
{
for (int j = i + 1; j < nodeList.Count; j++)
{
if (nodeList[i].Text.CompareTo(nodeList[j].Text)>0)
{
TreeNode temp = nodeList[i];
nodeList.RemoveAt(i);
nodeList.AddAt(i,nodeList[j-1]);
nodeList.RemoveAt(j);
nodeList.AddAt(j, temp);
}
}
}
return nodeList;
}
Example calling code:
var tncInOrder = SortTreeNode(this.MyTreeView.CheckedNodes);
foreach (TreeNode node in tncInOrder )
{
//Iterate through the nodes in order
}
Upvotes: 0
Reputation: 116987
CheckedNodes is a TreeNodeCollection which just implements ICollection. When the checkChanged event fires, it probably just adds the tree nodes to the CheckedNodes collection.
Nothing I can see on MSDN implies that you should assume the nodes would be ordered. All it says is:
Each time the page is posted to the server, the CheckedNodes collection is automatically populated with the selected nodes.
From your experiment, it seems safe to assume that on the second postback, it simply adds any new checked nodes to the collection, rather than clearing the collection and re-adding everything.
Upvotes: 2