Winfrom中ListBox綁定List數據源更新問題
摘自:http://xiaocai.info/2010/09/winform-listbox-datasource-update/
Winfrom中ListBox綁定List數據源,第一次可以成功,但后面List更新以后,ListBox並沒有更新。
如果 ListBox的數據源 是 DataTable 是可以自動更新的,但若是 List<T> 時對數據的修改界面不會更新,使用 BindingSource 綁定就可以了。
private void InitSample()
{
ListBox listControl = new ListBox();
List<Employee> listSource = new List<Employee>();
BindingSource bs = new BindingSource();
bs.DataSource = listSource;
listControl.DataSource = bs;
listControl.DisplayMember = “Name”;
listControl.ValueMember = “Id”;
// 事先綁定了,這時修改數據源會自動刷新界面顯示
listSource.Add(new Employee(1, “Sam”));
listSource.Add(new Employee(2, “John”));
this.Controls.Add(listControl);
}
補充:使用BindingList亦可解決此問題!