C# .Net – DataBinding using BindingList


The coding example used here are from .NetFramwork 4.0.

Overview

In this blog I would like demonstrate how easy it is to use System.ComponentModel.BindingList class to data-bind strongly typed classes to UI controls.

Traditional data-binding using DataTable

[TestMethod]
public void DataBindingWithDataTable() {
    DataTable contacts = new DataTable();

    contacts.Columns.Add("ID", typeof(int));
    contacts.Columns.Add("Name");
    contacts.Rows.Add(new object[] { 1, "Mike" });
    contacts.Rows.Add(new object[] { 2, "Joe" });

    Form frm = new Form();
    DataGrid grid = new DataGrid() { Dock = DockStyle.Fill, DataSource = contacts };
    frm.Controls.Add(grid);
    frm.ShowDialog();
}

Data-binding using BindingList<>

public class Contact {
    public int ID { get; set; }
    public string Name { get; set; }
}

[TestMethod]
public void DataBindingUsignBindingList() {
    BindingList<Contact> contacts = new BindingList<Contact>() {
        new Contact() { ID = 1, Name = "Mike" },
        new Contact() { ID = 2, Name = "Joe" }};

    Form frm = new Form();
    DataGrid grid = new DataGrid() { Dock = DockStyle.Fill, DataSource = contacts };
    frm.Controls.Add(grid);
    frm.ShowDialog();
}

Advertisements

Tags: , , ,

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


%d bloggers like this: