2

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?

techjourneyman
  • 1,701
  • 3
  • 33
  • 53

2 Answers2

5

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.

techjourneyman
  • 1,701
  • 3
  • 33
  • 53
  • i am facing the same problem, i am displaying the datagrid in tablelayout, can u tell me the way to solve it. – Mogli Nov 02 '13 at 14:09
  • how you did this can you please let us now my grid view is in tab and returning 1 always row count how to count rows of gridview that are present inTABS – office 302 Dec 29 '15 at 12:28
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.

KreepN
  • 8,528
  • 1
  • 40
  • 58
  • Unfortunately that did not fix the problem. – techjourneyman Jun 27 '12 at 14:41
  • My guess would be that you are somehow disposing of your data before it is being bound. Post up your code that fills the datatable and I'll take a look. Make sure you leave out the connectionstring and include your declarations as well so I can take a look at the scope of the variables. – KreepN Jun 27 '12 at 14:54