techjourneyman
techjourneyman

Reputation: 1813

Datagridview rowcount showing 0 even when there is a valid datasource

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?

Upvotes: 2

Views: 4497

Answers (2)

techjourneyman
techjourneyman

Reputation: 1813

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.

Upvotes: 5

KreepN
KreepN

Reputation: 8598

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.

Upvotes: 2

Related Questions