How to bind dataGridView predefined columns with columns from sql statement (without adding new columns)?

Jooj picture Jooj · Nov 16, 2009 · Viewed 47.1k times · Source

Is there a elegant way, to bind predefined dataGridView columns with results from a SQL statement?

Example:

dataGridView1.Columns.Add("EID", "ID");
dataGridView1.Columns.Add("FName", "FirstName");

Some SQL like

SELECT t.FirstName AS FName, t.EmpID AS EID 
FROM table t ...

and then I call

 dataGridView1.DataSource = someDataSet.Tables[0].DefaultView;

The last call add columns to my datagrid but I just want to bind it by column name not to add new columns.

The example will give a result like this:

Table columns: ID, FirstName, FName, EID (ID and FirstName holds empty cells)

How to get this:

Table columns: ID, FirstName or FirstName, ID

Best regards!

Answer

jaybz picture jaybz · Jan 26, 2010

Aside from setting AutoGenerateColumns to false, you also need to set DataPropertyName for each column in the DataGridView to the corresponding field in the data source. You can set this in the designer or in code before setting the DataSource property.