Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 990
Jooj Avatar asked Nov 16 '09 10:11

Jooj


3 Answers

Use dataGridView1.Columns["FName"].DataPropertyName = "FName" where FName is column in your data table.

like image 108
Iftikhar Avatar answered Nov 20 '22 10:11

Iftikhar


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.

like image 17
jaybz Avatar answered Nov 20 '22 09:11

jaybz


I think the DataGridView has an AutoGenerateColumns property, doesn't it?

dataGridView1.AutoGenerateColumns = True;

From the MSDN docs:

public bool AutoGenerateColumns { set; get; } Member of System.Windows.Forms.DataGridView

Summary: Gets or sets a value indicating whether columns are created automatically when the System.Windows.Forms.DataGridView.DataSource or System.Windows.Forms.DataGridView.DataMember properties are set.

Returns: true if the columns should be created automatically; otherwise, false. The default is true.

The property isn't on the Properties window though, you have to set it via code as in my example.

like image 4
Neil Barnwell Avatar answered Nov 20 '22 10:11

Neil Barnwell