How do I bind the result of DataTable.Select() to a ListBox control?

拜拜、爱过 提交于 2019-12-20 20:01:28

问题


I have the following code:

ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match")
ListBox.DisplayMember = "name"

The DataTable.Select() method returns an array of System.Data.DataRow objects.

No matter what I specify in the ListBox.DisplayMember property, all I see is the ListBox with the correct number of items all showing as System.Data.DataRow instead of the value I want which is in the "name" column!

Is it possible to bind to the resulting array from DataTable.Select(), instead of looping through it and adding each one to the ListBox?

(I've no problem with looping, but doesn't seem an elegant ending!)


回答1:


Use a DataView instead.

ListBox.DataSource = new DataView(DataSet.Tables("table_name"), "some_criteria = match", "name", DataViewRowState.CurrentRows);
ListBox.DisplayMember = "name"



回答2:


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.


 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.



来源:https://stackoverflow.com/questions/114851/how-do-i-bind-the-result-of-datatable-select-to-a-listbox-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!