且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何绑定的dataGridView与SQL语句中列预定义列(不添加新列)?

更新时间:2023-12-01 10:05:40

除了的AutoGenerateColumns设置为false,您还需要设置DataPropertyName用于在DataGridView到相应的字段的每一列中的数据源。您可以在设计还是在设置DataSource属性之前代码中设置这一点。


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!

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.