CR41G14
CR41G14

Reputation: 5594

Datagridview rows are 0 even though I have a datasource

I am programmatically creating a datagrid view and binding data to it. For some reason the rows are empty. Strange as it may seem but I do not want to display the Datagrid view just pass it into a class which extracts the data as Excel and CSV.

 this.DataGridView = new System.Windows.Forms.DataGridView();

  System.Windows.Forms.BindingSource bindingSource = new System.Windows.Forms.BindingSource();
            bindingSource.DataSource = DataSource;

  this.DataGridView.AutoGenerateColumns = autoGenerateColumns;
  this.DataGridView.DataSource = bindingSource;
  Int32 rowCount = this.DataGridView.Rows.Count; // 0!

Is there any way after creating the data source I can get the rows to populate?

Thanks

Upvotes: 2

Views: 5387

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

In order to see data grid, you should add it to parent controls collection:

DataGridView = new System.Windows.Forms.DataGridView();
Controls.Add(DataGridView);

Currently your grid do not have any parent and cannot be displayed.

Upvotes: 0

Chris
Chris

Reputation: 8647

I believe DataGridViews don't bind/contain any rows until they are actually rendered.

@paul.abbott.wa.us is right.

You can move the code that count the rows in DataGridView.DataBindingComplete Event

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.databindingcomplete.aspx

Upvotes: 1

Rwiti
Rwiti

Reputation: 1066

I wonder why you need a DataGridView without displaying it on the UI in the first place. There are couple of alternates I can suggest

  1. Let go the DataGridView and use DataTable/IEnumerable to keep the data. Both can provide you with counts.
  2. If you insist on keeping the DataGridView then something like

(Assuming its bound to a DataSet)

((DataSet)dataGridView1.DataSource).Tables[0].Rows.Count

would also work.

Upvotes: 1

Related Questions