Linq to DataGridView,AutoGenerateColumns = False显示空白行

时间:2016-11-16 07:23:34

标签: c# vb.net linq datagridview

我的DGV通过设计师预先格式化了列。使用SQL,我可以将SqlDataReader结果加载到DataTable,只需遍历列以在那里设置DataPropertyName属性。

我现在正在迁移到LINQ;使用以下内容将AutoGenerateColumns设置为False

Dim result = From a In db.states
             Select a

DataGridView1.DataSource = result

...似乎只显示一个空白网格(同时保留列)。救命?我希望尽可能在设计器上完成网格列的格式化。感谢。

更新

逐个设置DataPropertyName似乎有效:

col1.DataPropertyName = "id"
col2.DataPropertyName = "name"

有没有办法将它转换为例程,可能有一个循环,所以我不必手动设置所有内容?有点像(有一个DataTable):

For i = 0 To dt.Columns.Count - 1 : List.Columns(i).DataPropertyName = dt.Columns(i).ColumnName : Next

2 个答案:

答案 0 :(得分:0)

好像你仍然需要将它转换成这样的列表:

Dim result = From a In db.states
             Select a

DataGridView1.DataSource = result.ToList() 'converts to list

答案 1 :(得分:0)

尝试添加BindingSource:

Dim result = From a In db.states
             Select a

Dim bs = New BindingSource()
bs.DataSource = result
DataGridView1.DataSource = bs
相关问题