Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting blank rows after setting DataGridView.DataSource

Could somebody tell me why I'm getting blank rows after running this code?

...
dataGridView.AutoGenerateColumns = false; //must be false, else getting additional columns from SQL
dataGridView.DataSource = dataSet.Tables[0].DefaultView; 

Also tried

dataGridView.Update();

but not working.

Row count is ok, but why do I get blank rows?

I'm using Winforms.

like image 789
Jooj Avatar asked Nov 17 '09 14:11

Jooj


People also ask

How do you fix rows Cannot be programmatically added to the DataGridView rows collection when the control is data bound?

Solution 1 Either you strip off the data binding and do the boilerplate code yourself. Or you add a new record to the datasource and refresh the gridview => it will update itself with the new row.

How do you display data grids?

Step 1: Make a database with a table in SQL Server. Step 2: Create a Windows Application and add DataGridView on the Form. Now add a DataGridView control to the form by selecting it from Toolbox and set properties according to your needs.

How do I know if datagrid is empty?

You can find out if it is empty by checking the number of rows in the DataGridView. If myDataGridView. Rows. Count == 0 then your DataGridView is empty.

How do I add a row to a data grid?

You can add a single row of data by calling the AddData or AddLine commands of a Data Grid.


2 Answers

I found the problem.

I designed columns in the VS datagridview designer. Not the column name, but the column DataPropertyName must match with fields in database.

Then also duplicated columns will hide.

like image 130
Jooj Avatar answered Nov 13 '22 18:11

Jooj


Try something along these lines:

grid.AutoGenerateColumns = false;

DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Prop1";
col.HeaderText = "Property 1";
grid.Columns.Add(col);

col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Prop2";
col.HeaderText = "Property 2";
grid.Columns.Add(col);

grid.DataSource = dataSet.Tables[0].DefaultView;

Prop1 & Prop2 should match your table's column names. Property 1 & Property 2 is the header text to be displayed.

EDIT:

From the example you gave it looks like you're combining bound columns with unbound columns.

Do this:

1.Remove any columns added using the designer 2.Add this code:

grid.AutoGenerateColumns = false;

DataGridViewColumn colID = new DataGridViewTextBoxColumn();
colID.DataPropertyName = "customerID";
colID.HeaderText = "Ident.";
grid.Columns.Add(colID);

DataGridViewColumn colName = new DataGridViewTextBoxColumn();
colName.DataPropertyName = "customerFirstName";
colName.HeaderText = "First name";
grid.Columns.Add(colName);    
grid.DataSource = dataSet.Tables[0].DefaultView;

HTH.

like image 44
Sorin Comanescu Avatar answered Nov 13 '22 17:11

Sorin Comanescu