I'd like to show you how
easy it is to extend the TreeNode Class so that each Node in your TreeView can contain instantly accessible information of your choice. You don't need to sub-class the TreeView.
I'll start by defining a Class named 'Information:
public class Information
{
public string ID { get; private set; }
public string DeptName { get; private set; }
public string SubDeptName { get; private set; }
public Information(string id, string deptname, string subdeptname)
{
ID = id;
DeptName = deptname;
SubDeptName = subdeptname;
}
}
Why bother with a class, when we could just create a class that inherits from TreeNode in which you'd have fields ? The choice is based on the expectation that many nodes will share common Department Names and SubDeptNames, and using a Class means we stick a pointer to the same instance of 'Information into many Nodes ... hopefully that avoids a lot of duplicate strings.
The custom TreeNode Class:
public class TreeNodeEx : TreeNode
{
public Information NodeInformation { get; set; }
public TreeNodeEx(Information info)
{
NodeInformation = info;
this.Text = info.ID;
}
}
Let's look how we might create some instances of the custom TreeNode class:
private string id, dept, subdept;
id = "Marketing";
dept = "Advertising";
subdept = "Internet Ads";
Information info = new Information(id, dept, subdept);
for (int i = 0; i < 10; i++)
{
TreeNodeEx newNode = new TreeNodeEx(info);
treeView1.Nodes.Add(newNode);
}
How to access the extended information now in the custom TreeNode Class:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
TreeNodeEx selNode = treeView1.SelectedNode as TreeNodeEx;
}
You'll note that to access the extended information we had to cast the reference returned by treeView1.SelectedNode to our extended custom TreeNode Type. Without that cast there would be an error.
A nice feature of adding an instance of a Class to the custom TreeNode is that in Visual Studio when you inspect an instance of the TreeNode, you'll see the Class Name 'Information displayed separately in the pop-up, and you can open it easily to see the custom values.
You'll note the assumption made here that at the moment you create the TreeNodes you have, at hand, all the secondary information required to fill the fields of the instance of the 'Information class.