Posts Tagged ‘BindingList’

C# .Net – DataBinding using BindingList

March 20, 2010

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