views:

498

answers:

4

Hey,

Is there a elegant way, to bind predefined dataGridView columns with results from 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 coulumns: ID, FirstName, FName, EID (ID and FirstName holds empty cells)

How to get this:

Table coulumns: ID, FirstName or FirstName, ID

Best Regards!

A: 

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.

Neil Barnwell
Neil, tried dataGridView1.AutoGenerateColumns = True; and = false, but the same result. Doesn't work.
Jooj
Is this ASP.NET or WinForms?
Neil Barnwell
I'm using WinForms.
Jooj
Are you setting AutoGenerateColumns **before** setting DataSource or DataMember, as per the docs?
Neil Barnwell
Tried to set it before and after setting DataSource and still not what I need.
Jooj
The columns now are ok, but the rows are empty.
Jooj
Also the row count is ok, only the cells are empty.
Jooj
A: 

How about adding columns to the Columns tag of your gridview like so?

<Columns>
<asp:BoundField DataField="EID" HeaderText="ID" />
<asp:BoundField DataField="FName" HeaderText="First name" />
...
adrianos
Thanks, but I'm using winforms!
Jooj
ah, sorry, my mistake.
adrianos
A: 

Nobody knows???

Jooj
A: 

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.

jaybz