Reputation: 13602
I have a table named Department with 3 columns [DepartmentID, ParentDepID, DepartmentName]. Each Department may have a parent Department (ParentDepID) which can have a parent and so on. I want to load this data from sql-server
to a treeview
.
This is an imaginary exaple of data
DepID ------ ParentID ------- Name
1----------------Null------------HospitalA
2-----------------1--------------SurgeryDepartment
3-----------------1--------------CancerDepartment
4-----------------1--------------HeartDiseases
5-----------------2--------------BrainSurgery
6-----------------2--------------ChildBirth
7-----------------5--------------UpperBrainSurgery
8-----------------5--------------LowerBrainSurgery
this can go deeper (n) times, I want to load such data to my treeview.
What have I tried so far? Unfortunately I don't know how to do so, so please help me with the idea.
Upvotes: 0
Views: 429
Reputation: 2497
// Manage Tree View Nodes in RunTime
// In order to manage a node you should set a key for each node
// in your case records id's could be fine
treeView1.Nodes.Add("RootNode1Key","Root Node1");
treeView1.Nodes.Add("RootNode2Key", "Root Node2");
// adds a node in runtime with title Root Node
//Now add a Child to "Root Node 2"
// first find the node and make a pointer to it :^)
TreeNode FoundedNode;
FoundedNode = treeView1.Nodes.Find("RootNode2Key", true)[0];
// if you create a unique key for each node the find function returns
// a tree node array with only one node and you access it like above
// else you retrieve many records of TreeNode
FoundedNode.Nodes.Add("RootNode2Childe1", "Root Node2 Child 1");
// hey now you added a child node to RootNode2
// you want to add a child for it in depth
// 2 ways :
// 1: yous find method treeView1.Nodes.Find("RootNode2Childe1", true)[0];
// 2: Following
FoundedNode.Nodes["RootNode2Childe1"].Nodes.Add("RootNode2Childe1Child1", "my parent is RootNode2Childe1");
now if you want to remove one it's easy like following
private void button2_Click(object sender, EventArgs e)
{
// i am sure you know how to add nodes now remove a node
TreeNode FoundedNode;
FoundedNode = treeView1.Nodes.Find("RootNode2Childe1Child1", true)[0];
FoundedNode.Remove();
}
but i suggest you search the net there are some methods and better solutions you may use a data source and then when a record added to your table and a record removed then your tree view updates and vice versa
*Offer a member ship of this community to other Iranian guys and programmers *
Upvotes: 1
Reputation: 1063
First you need to add the root node(the most basic one without the parent) and then add the childnodes.. This link will help you : Populate TreeView from DataBase
Upvotes: 0