0

I have a DataGridView that I am using to put data in from an access database. I have it on the main form at the moment and when the form is open the grid is just greyed out.

When the button is clicked though, the information appears along with the columns. I would like the columns to be there before the button is clicked so when the form is opened you can see what the columns are minus the data.

I tried adding columns in design mode but when the button is clicked other columns simply get added on.

My current code is below.

string sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=Sailing.accdb";
OleDbConnection conSailing = new OleDbConnection(sConnection);
conSailing.Open();

string sQueryShipsPort = "Select ShipName, Weight FROM Ships WHERE Inport = True ;";
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sQueryShipsPort, conSailing);
DataSet ds = new DataSet();

dataadapter.Fill(ds, "Ships Table");
conSailing.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Ships Table";
David Hall
  • 32,624
  • 10
  • 90
  • 127
Moeii Younes
  • 1
  • 1
  • 1

1 Answers1

0

There are two things you will need to do to resolve this - first you need to tell the columns you create how they relate to your data table. Secondly you need to tell the data grid not to generate columns for you.

Databinding DataGridView columns to the data source

When you add a column to the grid using the designer you will see the option to edit this column. Select this and you will see a list of properties for a DataGridViewColumn.

The property you are interested in is DataPropertyName - this tells the column which property in the data source to bind to.

So if for example in your data table you have a column 'FirstName' you need to set DataPropertyName for the grid first name column you add to be 'FirstName'.

Stopping the grid from auto generating columns

The reason that you see more columns when you add your data source is that the DataGridView will automatically generate columns for you when you add the data source.

To turn this off all you need to do is set the DataGridView property AutoGenerateColumns to false. This can be done either through the designer or through code.

(Sometimes you don't need to do this - I've found that just setting the DataPropertyName will do often, but setting AutoGenerateColumns to false when you don't want it is generally good practice)

David Hall
  • 32,624
  • 10
  • 90
  • 127