LINQ Basic DataSource binding

This is a quick example of LINQ and binding to a DataGridView control (via DataSource) the property name is used as the column header (Column[idx].HeaderText) this can be change via the following attribute:
System.ComponentModel.DisplayName(“Column header name here”)

The following example uses a LINQ query on a string collection to demonstrate this:

C#

var objCollection = from objs in fileStringCollection
                    select new WrapperForStrings
                    {StringProperty = objs};
this.DataGridView2.DataSource = objCollection.ToList();
this.DataGridView2.AutoResizeColumns();
...
public class WrapperForStrings
{
    private String stringValue;

    [System.ComponentModel.DisplayName("Column header name here C#")]
    public String StringProperty
    {
        get
        {
            return stringValue;
        }
        set
        {
            stringValue = value;
        }
    }
}

VB.NET

Dim objCollection = From objs In fileStringCollection _
                    Select New WrapperForStrings _
                    With {.StringProperty = objs}
Me.DataGridView2.DataSource = objCollection.ToList()
Me.DataGridView2.AutoResizeColumns()
...
Public Class WrapperForStrings
    Private stringValue As String

    <System.ComponentModel.DisplayName("Column header name here VB")> _
    Public Property StringProperty() As String
        Get
            Return stringValue
        End Get
        Set(ByVal value As String)
            stringValue = value
        End Set
    End Property
End Class
Advertisements

One response to “LINQ Basic DataSource binding

  1. Pingback: LINQ Basic Selects | Tim's cycling blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s