.net 如何将数据绑定到 System.Windows.Forms.Treeview 控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/372820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you databind to a System.Windows.Forms.Treeview control?
提问by GWLlosa
I'm looking at this control, and it seems to be lacking the standard .net "datasource" and "datamember" properties for databinding. Is this control not bindable? I can write some custom function that populates the treeview from a given data source, I suppose, and embed data objects as necessary, but is that the 'best practice'? Or does everyone simply use a 3rd party treeview control?
我正在查看这个控件,它似乎缺少用于数据绑定的标准 .net“数据源”和“数据成员”属性。这个控件是不可绑定的吗?我想我可以编写一些自定义函数,从给定的数据源填充树视图,并根据需要嵌入数据对象,但这是“最佳实践”吗?还是每个人都只是使用 3rd 方树视图控件?
采纳答案by Gavin Miller
You are correct in that there is no data binding. The reason being is that TreeViews are hierarchical data structures. That is, not a straight list. As a result the databind option is invalid to say a List structure.
您是对的,因为没有数据绑定。原因是 TreeView 是分层数据结构。也就是说,不是一个直接的列表。因此,数据绑定选项对于表示 List 结构是无效的。
Sadly it's creating your own populate methods or buying 3rd party controls (which in the end will have their own populate methods.)
可悲的是,它正在创建您自己的填充方法或购买 3rd 方控件(最终将拥有自己的填充方法。)
Here's a decent MSDN article on Binding Hierarchical Data.
这是关于Binding Hierarchical Data的一篇不错的 MSDN 文章。
回答by TheCodeMonk
I use the tree control from Developer's Express. It will take a table of data and display/edit it in a hierarchical fashion.
All it needs is a primary key field and a parent id field in the table and it can figure out what goes where.
我使用 Developer's Express 中的树控件。它将采用一个数据表并以分层方式显示/编辑它。
它所需要的只是表中的一个主键字段和一个父 id 字段,它可以找出去哪里。
You can do the same thing if you roll your own code and use your own class.
如果您使用自己的代码并使用自己的类,则可以执行相同的操作。
class Node
{
System.Collections.Generic.List<Node> _Children;
String Description;
void Node()
{
_Children = new System.Collections.Generic.List<Node>();
}
public System.Collections.Generic.List<Node> Children()
{
return (_Children);
}
}
class Program
{
static void Main(string[] args)
{
System.Collections.Generic.List<Node> myTree = new System.Collections.Generic.List<Node>();
Node firstNode = new Node();
Node childNode = new Node();
firstNode.Children().Add(childNode);
}
}
回答by dotjoe
If it's only a couple levels, I like to populate a dataset with a couple tables and set up a DataRelation on the columns. Then you use some nested loops and create your tree nodes.
如果它只有几个级别,我喜欢用几个表填充数据集并在列上设置 DataRelation。然后使用一些嵌套循环并创建树节点。

