[英]C# Program crashes when removing item from ListBox
I am using a BindingList as a datasource for my ListBox. 我正在使用BindingList作为ListBox的数据源。
public static BindingList<memo> memosList = new BindingList<memo>();
Whenever I attempt to remove the selected object (via a button), my program crashes. 每当我尝试删除选定的对象(通过按钮)时,我的程序就会崩溃。
private void editMemo_Click(object sender, EventArgs e)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
I get the following error: 我收到以下错误:
An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll System.Windows.Forms.dll中发生了类型为'System.ArgumentException'的未处理异常
Additional information: Items collection cannot be modified when the DataSource property is set. 附加信息:设置DataSource属性时,不能修改Items集合。
I have also tried to use: 我也尝试使用:
private void editMemo_Click(object sender, EventArgs e)
{
Form2.memosList.Remove(listBox1.SelectedIndex);
}
however this will not allow me to compile. 但是,这不允许我进行编译。
What can I do to remove the item without throwing an exception? 如何在不引发异常的情况下删除项目?
You should remove the item from the BindingList that you have binded to the DataSource of your list 您应该从BindingList中删除已绑定到列表的DataSource的项目。
private void editMemo_Click(object sender, EventArgs e)
{
if(listBox1.SelectedItem != null)
{
BindingList<memo> bl = listBox1.DataSource as BindingList<memo>;
bl.Remove(listBox1.SelectedItem as memo) ;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.