RSS

Dynamic Add Data into TreeView in C#

27 May

This technique apply for nested data store on relational dbms, for examples:

Table1
+——–+——–+———-+
|  ID     |  Name  | ParentID |
+——–+——–+———-+
|  1     |  A     | 0        |
|  2     |  B     | 0        |
|  3     |  C     | 0        |
|  4     |  a     | 1        |
|  5     |  b     | 1        |
|  6     |  c     | 2        |
|  7     |  d     | 3        |
|  8     |  e     | 3        |
+——–+——–+———-+

And we want to show in Treeview control as:

TreeviewControl
+–
|-A-
|-a
|-b
|
|-B-
|-c
|
|-C-
|-d
|-e

So we do not need to use [Loop] to insert sub tree in to other tree.

IEnumerable<Table1> dataCollection =  // From table [Table1] “in Linq code”;

foreach(var record in dataCollection)
{
if(record.ParentID == 0)
{
TreeviewControl.Nodes.Add(record.ID.toString(), record.Name);
}
else
{
TreeNode[] tn = TreeviewControl.Nodes.Find(record.ParentID.toString(), true);
tn[0].Nodes.Add(record.ID.toString(), record.Name);
}

Advertisements
 
Leave a comment

Posted by on May 27, 2011 in C#, Window Application

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: