I was writing a method to add
Nodes
to a
TreeView
.
The nodes at different levels represented different types of data, each type was implemented as a lightweight class. Because I wanted to make adding the nodes as simple as possible I had overridden the
ToString()
method of each to return the text as I wanted it to appear in the TreeView.
I decided that it would be easiest to write one method that could add any of the classes I intended to use and the obvious way to do that was to write a
Generic Method
and pass it the parent node and a list of items to be added to the parent.
All went well until I noticed that the nodes were unsorted. I quickly added
nodeData.Sort();
and of course this raised an
InvalidOperationException
"Failed to compare two elements in the array."
I started to edit my classes to make them implement
IComparable
but there were a lot of them and it occurred to me that this would be a good use of an
Anonymous Delegate
.
Here is an abbreviated version of the method concerned:
private bool FillNode<T>(TreeNode aNode, List<T> nodeData)
{
bool result = false;
this.myTreeView.BeginUpdate();
try
{
if ((aNode.Nodes.Count == 1) && string.IsNullOrEmpty(aNode.Nodes[0].Name))
{
aNode.Nodes.Clear();
}
nodeData.Sort((a, b) => a.ToString().CompareTo(b.ToString()));
foreach (T ad in nodeData)
{
TreeNode newNode = new TreeNode(ad.ToString());
newNode.Tag = ad;
if (aNode.Level < 5)
{
newNode.Nodes.Add("");
}
aNode.Nodes.Add(newNode);
}
result = true;
}
finally
{
this.myTreeView.EndUpdate();
}
return result;
}
This was made easier because I had already overridden the ToString() method.