Assuming that you need to make this generic, i.e. that your database may contain other results, the first thing to do is to create a framework that reads the database and calls a method to add each node in turn. The hardwired version of this is:
AddNode(myTreeView, 1001, "a", 1000);
AddNode(myTreeView, 1002, "b", 1001);
AddNode(myTreeView, 1003, "c", 1002);
AddNode(myTreeView, 1004, "d", 1003);
AddNode(myTreeView, 1005, "e", 1001);
So, you need to write the AddNode method. But first, how are you going to store this? A TreeNode can only store text, and a Tag value. I would suggest that you first create a class to hold your node information, and put that into your TreeNode Tag:
public class myNode
{
public int ID { get; set; }
public string Name { get; set; }
public myNode(int id, string name)
{
ID = id;
Name = name;
}
}
Nice and simple, but can be expanded.
Now, AddNode is simple, but since this is your homework, I'm not giving you the actual code!
1) Create a new myNode instance.
2) Create a new TreeNode instance. Set the new TreeNode.Tag property to the myNode instance
3) Find the parent node you need to attach to.
4) If it exists, add a new node to it. Otherwise, add the new node to the TreeView root.
Find the parent node is slightly more complex: you need recursion, so create a new method:
private TreeNode FindNode(TreeNodeCollection nodes, int id)
You will initially call this with the Nodes property of your TreeView:
TreeNode t = FindNode(treeView.Nodes, parentId);
FindNode isn't difficult either:
1) If nodes has no items, return null - it isn't in this list.
2) Loop through each node in nodes (look at a foreach loop)
2a) Cast the node.Tag property to a myNode instance (it is a very good idea to check it is a myNode before you try to use it)
2b) If the ID property matched the ID you are looking for, return this node.
2c) Otherwise, call FindNode on the node.Nodes property of this node.
2d) If the node is found, return it. (this passes the found node all the way back up the chain)
2e) Otherwise, try the next node in the list
3) If you run out of nodes without finding the ID you are looking for, return null.
Sounds complex? A bit. But in practice, the code for each part is pretty simple, and actually takes less space that the description above!
Try it - it isn't really difficult, and if you get stuck, ask!