binding a set of datarows to datagridview

随声附和 提交于 2019-12-02 05:30:22

问题


I have tried the following code, but nothing is displayed in datagridview.

Any Suggestions?

string strFilterOption = "dtcolnPurchaseProductExpProductNo=270";
dgvProductExp.DataSource = dtPurchaseProductExp.Select(strFilterOption);

回答1:


From MSDN

The DataGridView class supports the standard Windows Forms data-binding model. This means the data source can be of any type that implements one of the following interfaces:

The IList interface, including one-dimensional arrays.

The IListSource interface, such as the DataTable and DataSet classes.

The IBindingList interface, such as the BindingList class.

The IBindingListView interface, such as the BindingSource class.

Due to the default behavior for databinding with array, you can't set, for the DataSource property, the array of Datarows that the Datatable.Select method will return. From this post:

The primary one is that the object implements IList or is a 1-Dimensional Array. The thing is, an array has a default behavior for databinding - Reflection. The object type within the array is reflected to discover its public properties which are not indexed and with value types that can be represented in the grid. These properties are then used as the Fields when the databinding occurs. Since the data type in your array is DataRow, there are six public properties: HasErrors, Item, ItemArray, RowError, RowState, and Table. But Item is an indexed property and ItemArray is of type Object(), which can't be displayed in a gridview, so these two properties are ignored and the other four are shown in the grid.

So another way would consist to create a new DataTable, using Clone method in order to get the schema from the DataTable source, and populate the new DataTable with the array of DataRows.

string strFilterOption = "dtcolnPurchaseProductExpProductNo=270";
DataTable cloneTable;
cloneTable = dtPurchaseProductExp.Clone();
foreach (DataRow row in dtPurchaseProductExp.Select(strFilterOption))
{
   cloneTable.ImportRow(row);
}
dgvProductExp.DataSource = cloneTable;

Or, you can also do your binding through a BindingSource object and use its Filter property.




回答2:


Have you test dgvProductExp.DataSource.Tables(0).Rows.Count ? .. if it show 0 that's why ..

Or are you sure it's not

string strFilterOption = "dtcolnPurchaseProductExpProductNo='270'"; ?




回答3:


In case if someone experiencing a similar issue, the easiest way will be to convert the data row array back to datatable and then setting the grid view data source.

dgvProductExp.DataSource = dtPurchaseProductExp.Select(strFilterOption).CopyToDataTable();


来源:https://stackoverflow.com/questions/17468390/binding-a-set-of-datarows-to-datagridview

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