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?
Replace
List<String>withBindingList<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 wayListBoxwould know that a new element is added. However, if you use a collection that implements IBindingList Interface, ListBox subscribes toListChangedevent. This is how it know when to refresh itself.