I got a assignment to Sort a TreeView on a application.., It had some elements already. Once user addes a new element it has to be get sorted among exsisting elements. I searched on the net, But no sucess. Finally, I have implemented my own method, Here I hope to share that with you all...
First Implement a "IComparable" class :
private class TreeSort : IComparable
{
private TreeNode _tvNode;
public TreeNode tvNode { get { return _tvNode; } set { _tvNode = value; } }
public TreeSort (TreeNode tvnode) { _tvNode = tvnode; }
public int CompareTo(object obj)
{
if (obj is TreeSort)
{
TreeSort ts = (TreeSort)obj;
return _tvNode.Text.CompareTo(ts.tvNode.Text); } return 0;
}
}
Now add follwoing code and call where ever you want to Sort the tree:
private void Sort(ref TreeView tv)
{
//------------------------------------------------------------
ArrayList UserVar = new ArrayList( tv.Nodes.Count );
foreach ( TreeNode childNode in tv.Nodes )
{
UserVar.Add( new TreeSort(childNode));
}
UserVar.Sort( ); //Sorting takes place here
//------------------------------------------------------------
tv.Nodes.Clear(); //Remove all nodes from tree
//------------------------------------------------------------
TreeNode root = new TreeNode("User Variables");
foreach(TreeSort ts in UserVar)
{
TreeNode tn = ts.tvNode;
root.Nodes.Add(tn);
}
tv.Nodes.Add(root);
root.Expand();
if(root.Nodes.Count>0) tv.SelectedNode = root.Nodes[0];
//------------------------------------------------------------
}
No comments:
Post a Comment