本文介绍了从DataTable填充TreeView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在数据库中创建了一个帐户表,其中包含以下列:

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

但是公司名称并非来自数据库,它来自代码。那么,如何像这样扩展 TreeView

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

如何在C#中做到这一点?我也从中尝试过,但我仍然不明白。

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

推荐答案

我花了2h编写复杂的算法后发现了一段对我有用的代码:

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);
 }

然后创建TreeNodePopulate事件:

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 !

这篇关于从DataTable填充TreeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:27