Posted by: Cirilo Meggiolaro | 02/20/2009

Tip of the day #129 – BindingList class

The object we are going to check today is often used to substitute a DataTable when binding data to controls such as ListBox, ComboBox and Grids. Available under the namespace System.ComponentModel, the generic BindingList<T> object contains operations, properties and events to control the insert, update and delete of items into the collection.

Public Methods

T AddNew(): Adds a new item to the collection;
void CancelNew(int itemIndex): Discards a pending new item;
void EndNew(int itemIndex): Commits a pending new item to the collection;
void ResetBindings(): Raises a ListChanged event of type ListChangedType.Reset;
void ResetItem(int position): Raises a ListChanged event of type ListChangedType.ItemChanged for the item at the specified position.

Main Properties

bool AllowEdit: Gets or sets a value indicating whether items in the list can be edited;
bool AllowNew: Gets or sets a value indicating whether you can add items to the list using the AddNew() method;
bool AllowRemove: Gets or sets a value indicating whether you can remove items from the collection;
bool RaiseListChangedEvents: Gets or sets a value indicating whether adding or removing items within the list raises ListChanged events.

Events

AddingNewEventHandler AddingNew: Occurs before an item is added to the list;
ListChangedEventHandler ListChanged: Occurs when the list or an item in the list changes.

How to…

The code I am posting here is a Windows Forms application that contains a ListBox control named lstProducts and two buttons: one named btnAddNew that uses the AddNew() operation to raise the AddingNew event and from there add a new item and a second button named btnChangeList that push a new item to the collection manually. The code is commented and self explanatory:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Stores the binding list of products.
    /// </summary>
    BindingList<Product> _products;

    private void Form1_Load(object sender, EventArgs e)
    {
        /// Calls the method that sets
        /// the list properties.

        SetList();

        /// Populates the BindingList events.
        PopulateList();

        /// Binds the ListBox control.
        BindList();

        /// Register the BindingList events.
        RegisterEvents();
    }

    private void SetList()
    {
        /// Instantiates the BindingList
        _products = new BindingList<Product>();

        /// Allows items to be added to the BindingList.
        _products.AllowNew = true;

        /// Disable the ability to edit
        /// items to the BindingList.
        _products.AllowEdit = false;

        /// Disable the ability to remove
        /// items to the BindingList.
        _products.AllowRemove = false;

        /// Sets the flag that indicates whether
        /// the BindingList raises the ListChanged
        /// event.
        _products.RaiseListChangedEvents = true;
    }

    private void PopulateList()
    {
        /// Loop to add new products
        /// to the BindingList.
        for (int i = 1; i <= 10; i++)
        {
            _products.Add(new Product() { ID = i, Name = “Product “ + i });
        }
    }

    private void BindList()
    {
        /// Sets the ListBox datasource.
        lstProducts.DataSource = _products;
        lstProducts.DisplayMember = “Name”;
        lstProducts.ValueMember = “ID”;
    }

    private void RegisterEvents()
    {
        /// Adds the AddingNew event handler.
        _products.AddingNew += new AddingNewEventHandler(products_AddingNew);

        /// Adds the ListChanged event handler.
        _products.ListChanged += new ListChangedEventHandler(products_ListChanged);
    }

    void products_AddingNew(object sender, AddingNewEventArgs e)
    {
        /// Assigns to the item being added
        /// a new instance of product.
        e.NewObject = new Product() { ID = _products.Count + 1, Name = “Product “ + (_products.Count + 1) };
    }

    void products_ListChanged(object sender, ListChangedEventArgs e)
    {
        /// Displays the change type.
        MessageBox.Show(“Change type: “ + e.ListChangedType.ToString());
    }

    private void btnChangeList_Click(object sender, EventArgs e)
    {
        /// Adds a new product to the BindingList.
        /// This add raises the ListChanged event.

        _products.Add(new Product() { ID = _products.Count + 1, Name = “Product “ + (_products.Count + 1) });
    }

    private void btnAddNew_Click(object sender, EventArgs e)
    {
        /// Adds a new item and raises
        /// the AddingNew event.
        _products.AddNew();
    }
}

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

Advertisements

Responses

  1. “A complete example” you posted. Excellent!
    By the way, got a Itaipava by my side… :) Carnaval!


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

Categories

%d bloggers like this: