AwonDanag AwonDanag - 17 days ago 7
Vb.net Question

Linq to DataGridView, AutoGenerateColumns = False displays blank rows

My DGV has pre-formatted columns via the designer. With SQL, I could load the

SqlDataReader
result to a
DataTable
and simply loop through the columns to set the
DataPropertyName
property there.

I'm now migrating to LINQ; setting the
AutoGenerateColumns
to
False
with:

Dim result = From a In db.states
Select a

DataGridView1.DataSource = result


...seems to only display a blank grid (while retaining the columns). Help? I want formatting of the grid columns to be done at the designer as much as possible. Thanks.

UPDATE

Setting the
DataPropertyName
one by one seems to work:

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


Is there a way to convert this to a routine, possibly with a loop, so I don't have to set everything manually? Kinda like this (with a
DataTable
):

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

Answer

Seems like you still need to convert this into list like so:

Dim result = From a In db.states
             Select a

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