Ken Tucker Blog

Adventures in .net

Datagridview and Linq issue

Monday, January 28, 2008

I had some one ask me an interesting question about using linq with the datagridview

When I bind a datagridview to this query

Dim names() As String = {"hello11", "hello212", "hello123", "hello124", "hello2325", "hello336", "hello457"}
Dim query = From s In names _
            Order By s _
            Select s
Dim bs As New BindingSource
bs.DataSource = query
DataGridView1.DataSource = bs

Why do I get these results?

image

The answer the datagridview will show the properties of the class in the list bound to the datagridview.  In this case we are bound to a list of string and the only bindable property is its Length.  

If you change the query to this

Dim names() As String = {"hello11", "hello212", "hello123", "hello124", "hello2325", "hello336", "hello457"}
Dim query = From s In names _
            Order By s _
            Select New With {.Name = s}
Dim bs As New BindingSource
bs.DataSource = query
DataGridView1.DataSource = bs

You will get the expected results

image  

I should also mention that you can not bind a datagridview to a linq query directory.  You need to bind the query to a bindingsource and bind the datagridview to the bindingsource or bind the datagridview to the queries ToList method.



kick it on DotNetKicks.com
Filed Under: DataGridView, Linq, VB

Comments (7) -

SSNLocator said:

great stuff mate..
thanks for sharing..

Busby SEO Test said:

Nice posting .. thank for info boss

Busby SEO Test Pinay said:

I am using WLW with BE.NET without any problem (well I do not count images created with https URL when posted by Metawebblog API with SSL enabled). If you have not yet tried, give it a second chance with the latest BE.NET 1.4.5.7 and this WLW tech preview

Busby SEO Test said:

closing the gap here.

Busby SEO Test said:

to create datagride view you nead to change the query. thank for share this.

Comments are closed