.net 如何将 DataTable.Select() 的结果绑定到 ListBox 控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/114851/
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 I bind the result of DataTable.Select() to a ListBox control?
提问by Andrew
I have the following code:
我有以下代码:
ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match")
ListBox.DisplayMember = "name"
The DataTable.Select()methodreturns an array of System.Data.DataRowobjects.
该DataTable.Select()方法返回一个System.Data.DataRow对象数组。
No matter what I specify in the ListBox.DisplayMemberproperty, all I see is the ListBox with the correct number of items all showing as System.Data.DataRowinstead of the value I want which is in the "name"column!
无论我在ListBox.DisplayMember属性中指定什么,我所看到的都是 ListBox,其中显示的项目数量正确,System.Data.DataRow而不是"name"列中我想要的值!
Is it possible to bind to the resulting array from DataTable.Select(), instead of looping through it and adding each one to the ListBox?
是否可以从 绑定到结果数组DataTable.Select(),而不是遍历它并将每个数组添加到ListBox?
(I've no problem with looping, but doesn't seem an elegant ending!)
(我对循环没有问题,但似乎不是一个优雅的结局!)
回答by Josh
回答by t3rse
Josh has it right with the DataView. If you need a very large hammer, you can take the array of rows from any DataTable.Select("...") and do a merge into a different DataSet.
Josh 对 DataView 非常了解。如果您需要一个非常大的锤子,您可以从任何 DataTable.Select("...") 中获取行数组并合并到不同的 DataSet 中。
DataSet copy = new DataSet();
copy.Merge(myDataTable.Select("Foo='Bar'"));
// copy.Tables[0] has a clone
That approach for what you're trying to do is most probably overkill but there are instances when you may need to get a datatable out of an array of rows where it's helpful.
对于您尝试做的事情,这种方法很可能是矫枉过正,但在某些情况下,您可能需要从行数组中获取数据表,这很有帮助。

