Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have created an account table in my database, with these columns:

ID
Name
ParentID

This is an example of how records have been stored:

ID   Name    ParentID
1    BANK A  0
2    0001    1
3    0002    1
4    BANK B  0
5    0001    4
6    0002    4

But the company name does not come from database, it comes from code. So how can I expand the TreeView like this?

├─ BANK A
│  ├─ 0001
│  └─ 0002
└─ BANK B
   ├─ 0001
   └─ 0002

How can I do this in C#? I also tried from HERE but I still don't understand it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
571 views
Welcome To Ask or Share your Answers For Others

1 Answer

i have found a piece of code that worked great for me after spending 2h to make complicated algorithlms :

 //In Page load
 //select where id is null to retrieve the parent nodes 
 //in a datatable (called table here)
 foreach (DataRow row in table.Rows)
 {
   TreeNode node = new TreeNode();
   node.Text = row["title"].ToString();
   node.Value = row["id"].ToString();
   //you can affect the node.NavigateUrl

   node.PopulateOnDemand = true;
   TreeView1.Nodes.Add(node);
 }

then create the TreeNodePopulate event :

 protected void TreeView1_TreeNodePopulate(Object sender, TreeNodeEventArgs e)
 {
     string id= e.Node.Value;
     //do your "select from yourTable where parentId =" + id;

     foreach (DataRow row in table.Rows)
     {
         TreeNode node = new TreeNode(row["title"], row["id"])
         node.PopulateOnDemand = true;    
         e.Node.ChildNodes.Add(node);
     }

 }

it worked like hell for me, i hope it will help !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...