Datagridview rowcount showing 0 even when there is a valid datasource

∥☆過路亽.° 提交于 2019-11-28 10:07:18

问题


I have a dynamically created DataGridView that has a valid DataSource with one row bound to it. However, it is returning me 0 when I am doing a rowcount on the DataGridView.

dgResult.DataSource = resultDt; // a datatable containing one row
flowLayoutPanel.Controls.Add(dgResult); 
int rows = dgResult.Rows.Count; // returning 0 always!

Can someone please tell me where I may be going wrong here?


回答1:


I found the issue. I was displaying the grid in a tabbed page that was not selected. Unless the grid is visible, it does not raise the rowadded event (which is weird!) durnig databinding. I selected the tab page before doing the databind, and the rowcount worked.




回答2:


Use this code instead:

BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = resultDt;

dgResult.DataSource = bindingSource;
flowLayoutPanel.Controls.Add(dgResult); 

var c = dgResult.Rows.Count;

The binding source is what's responsible for syncing your data with the control. You want to use it, rather than trying to assign the table directly to the control.



来源:https://stackoverflow.com/questions/11212086/datagridview-rowcount-showing-0-even-when-there-is-a-valid-datasource

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