为何List数据无法在ListBox中显示?C# WinForms绑定问题求助
问题描述
刚接触编程几天,遇到代码无法正常运行的问题:点击按钮向集合添加数据时,ListBox无法显示新数据,但把添加代码写在Form构造函数里就能正常显示。
原代码:
public partial class Form1 : Form { List<String> names = new List<String>(); BindingSource namesBindingSource = new BindingSource(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (CmdClockInOut.Text == "XYZ") { names.Add("123"); } } private void Form1_Load(object sender, EventArgs e) { namesBindingSource.DataSource = names; listBox1.DataSource = namesBindingSource; } }
构造函数中能正常显示的代码:
public Form1() { InitializeComponent(); namesBindingSource.DataSource = names; listBox1.DataSource = namesBindingSource; names.Add("123"); }
原因分析
List<string>是普通集合,不具备数据变更通知能力。构造函数里添加数据时,处于控件初始化绑定的流程中,ListBox会一次性加载集合内所有数据;而按钮点击添加数据是在绑定完成后操作的,集合内容变化后,没有机制通知BindingSource和ListBox“数据已更新需刷新”,因此ListBox不会显示新元素。
解决方案
有两种常用解决方式:
方式一:用BindingList<string>替代List<string>
BindingList<T>是为数据绑定设计的集合,自带数据变更通知机制,添加/删除元素时会自动触发BindingSource更新,ListBox同步刷新。修改代码如下:
// 将List<String>替换为BindingList<String> BindingList<String> names = new BindingList<String>(); BindingSource namesBindingSource = new BindingSource(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (CmdClockInOut.Text == "XYZ") { names.Add("123"); // 无需额外代码,BindingList会自动通知刷新 } } private void Form1_Load(object sender, EventArgs e) { namesBindingSource.DataSource = names; listBox1.DataSource = namesBindingSource; }
方式二:手动通知BindingSource刷新
如果坚持使用List<string>,每次修改集合后调用BindingSource.ResetBindings(false),手动通知BindingSource数据已变更,触发ListBox刷新:
private void button1_Click(object sender, EventArgs e) { if (CmdClockInOut.Text == "XYZ") { names.Add("123"); // 手动触发BindingSource刷新数据 namesBindingSource.ResetBindings(false); } }
内容的提问来源于stack exchange,提问作者Laqon
相关产品推荐
相关产品推荐

