How to refresh DataSource of a ListBox
listbox1.DataSource
property looks for value changes but by assigning the same list all the time the value won't really change.
You can use a BindingList<T>
, instead of your List<T>
, to automatically recognize new items added. Your ShowData() method must be called once at startup.
public partial class MyForm:Form
{
public MyForm(){
InitializeComponent();
ShowData();
}
BindingList<MyData> data = new BindingList<MyData>();
private void ShowData()
{
listBox1.DataSource = data;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
}
private void buttonAddData_Click(object sender, EventArgs e)
{
var selection = (MyData)comboBox1.SelectedItem;
data.Add(selection);
}
}
I would suggest to use BindingSource
as it would properly update connected controls.
public partial class MyForm : Form
{
List<MyData> data = new List<MyData>();
BindingSource bs = new BindingSource();
public MyForm()
{
IntializeComponents();
bs.DataSource = data;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
listBox1.DataSource = bs;
}
private void buttonAddData_Click(object sender, EventArgs e)
{
var selection = (MyData)comboBox1.SelectedItem;
data.Add(selection);
bs.ResetBindings(false);
}
}
Changing controls data source on fly produces strange result sometime.