如何将 dataGridView 预定义列与 sql 语句中的列绑定(不添加新列)?
有没有一种优雅的方法,将预定义的 dataGridView 列与 SQL 语句的结果绑定?
示例:
dataGridView1.Columns.Add("EID", "ID");
dataGridView1.Columns.Add("FName", "FirstName");
一些 SQL 类似
SELECT t.FirstName AS FName, t.EmpID AS EID
FROM table t ...
,然后我调用
dataGridView1.DataSource = someDataSet.Tables[0].DefaultView;
最后一个调用将列添加到我的数据网格,但我只想按列名称绑定它而不是添加新列。
该示例将给出如下结果:
表列:ID、FirstName、FName、EID(ID 和 FirstName 包含空单元格)
如何获取此结果:
Table columns: ID, FirstName or FirstName, ID
致以诚挚的问候!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
dataGridView1.Columns["FName"].DataPropertyName = "FName"
,其中 FName 是数据表中的列。Use
dataGridView1.Columns["FName"].DataPropertyName = "FName"
where FName is column in your data table.除了将
AutoGenerateColumns
设置为 false 之外,您还需要将DataGridView
中每一列的DataPropertyName
设置为数据源中相应的字段。您可以在设置DataSource
属性之前在设计器或代码中进行设置。Aside from setting
AutoGenerateColumns
to false, you also need to setDataPropertyName
for each column in theDataGridView
to the corresponding field in the data source. You can set this in the designer or in code before setting theDataSource
property.我认为 DataGridView 有一个 AutoGenerateColumns 属性,不是吗?
来自 MSDN 文档:
不过,该属性不在“属性”窗口中,您必须像我的示例中那样通过代码进行设置。
I think the DataGridView has an
AutoGenerateColumns
property, doesn't it?From the MSDN docs:
The property isn't on the Properties window though, you have to set it via code as in my example.
如果您正在使用 WinForm,重要的部分是设置
DataPropertyName
属性以匹配 DataTable 列名称。您可以在设计器或代码中执行以下操作:当然,已经设置了:
If you are doing WinForm, the important part is setting the
DataPropertyName
property to match the DataTable Column name. You can do it in the designer or code as follows:Of course, having set this:
像这样将列添加到 gridview 的 Columns 标签怎么样?
How about adding columns to the Columns tag of your gridview like so?