Using List of objects as Datasource

Bind List of Class objects as Datasource to DataGridView

Added by Nasir Mahmood updated on Friday, December 20, 2013

Problem:

We want to bind List of class objects to DataGridView as DataSource

Introduction:

Using DataTable as DataSource to DataGridView as binding is an easy task, on the other hand using List<Class Objects> as DataSource is little tricky. In this tutorial we learn how we can bind List<Class Objects> to DataGridView as DataSource. Let’s start

Person Class:

For test purpose we are creating a Person class as shown below

public class Person
{
    public int id { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string address { get; set; }
}

Generate Test Data and Bind:

Now create a list of Person class as shown below

List<Person> plist = new List<Person>();

In this step we will generate dummy data and try to bind to DataGridView as DataSource

for (int i = 0; i < 100; i++)
{
    plist.Add(new Person()
    {
        id = i,
        firstname = "First Name " + i,
        lastname = "Last Name " + i,
        address = "Address of person " + i
    });
}
dataGridView1.DataSource = plist;

Result is shown below

bind class as datasource to datagridview

Its looks as simple as DataTable so what’s new in this tutorial. Wait a minute and try to add a new person in list as and refresh DataSource we will notice that new data is not updated as we want.

Trick:

Here is a tricky part of this tutorial, by using ToList() extension method we can resolve this issue.

dataGridView1.DataSource = plist.ToArray();

Custom Header Text:

We can also change the header text of DataGridView column by using DisplayName attribute. Now our modified code Person class is shown below.

public class Person
{
    [DisplayName("ID")]
    public int id { get; set; }
    [DisplayName("First Name")]
    public string firstname { get; set; }
    [DisplayName("Last Name")]
    public string lastname { get; set; }
    [DisplayName("Address")]
    public string address { get; set; }
}

Check the result as shown below

bind class as datasource to datagridview and custom header text

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected