我有一个列表框,我想选择其中的项目,然后按按钮将其从数据库中删除。我可以编辑和保存,只是不能删除。
当前代码:
private void button1_Click_3(object sender, EventArgs e)
{
if (listBox1.Items.Count >= 1)
{
if (listBox1.SelectedValue != null)
{
listBox1.Items.Remove(listBox1.SelectedItem);
System.Windows.Forms.MessageBox.Show("Item Deleted");
}
}
else
{
System.Windows.Forms.MessageBox.Show("No ITEMS Found");
}
}
我收到错误:
Items collection cannot be modified when the DataSource property is set.
最佳答案
private void button1_Click_3(object sender, EventArgs e)
{
if (listBox1.Items.Count >= 1)
{
if (listBox1.SelectedValue != null)
{
var items = (List<YourType>)listBox1.DataSource;
var item = (YourType)listBox1.SelectedValue;
listBox1.DataSource = null;
listBox1.Items.Clear();
items.Remove(item);
listBox1.DataSource = items;
}
}
else
{
System.Windows.Forms.MessageBox.Show("No ITEMS Found");
}
}
这会起作用
关于c# - 使用窗口窗体中的按钮从列表框中删除所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50552465/