Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms binding question

I am relatively new to binding in win forms. In order to learn the subject I setup the following test application. A basic winform with a ListBox and a Button.

public partial class Form1 : Form
{
    public List<String> stringList = new List<String>();

    public Form1()
    {
        InitializeComponent();
        stringList.Add("First");
        listBox1.DataSource = stringList;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        stringList.Add("Second");
    }
}

The string "First" shows in listBox1 on application launch. However, when I push the button which adds a new string to the stringList the new item is not shown in listBox1. Could anyone help me understand the basics of collection data binding?

like image 852
DoubleDunk Avatar asked Jun 16 '11 05:06

DoubleDunk


1 Answers

Replace List<String> with BindingList<String>.

The BindingList class can be used as a base class to create a two-way data-binding mechanism. BindingList provides a concrete, generic implementation of the IBindingList interface.

List<T> class does not provide any notification about collection changes. So there is no way ListBox would know that a new element is added. However, if you use a collection that implements IBindingList Interface, ListBox subscribes to ListChanged event. This is how it know when to refresh itself.

like image 130
Alex Aza Avatar answered Nov 10 '22 19:11

Alex Aza