Reputation: 5594
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
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
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
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
(Assuming its bound to a DataSet)
((DataSet)dataGridView1.DataSource).Tables[0].Rows.Count
would also work.
Upvotes: 1