首页 > 解决方案 > 使用窗口窗体中的按钮从列表框中删除所选项目

问题描述

我有一个列表框,我想在其中选择和项目,然后按一个按钮从数据库中删除它。我可以很好地编辑和保存,只是不能删除。

当前代码:

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");
     }
}

我收到错误消息:

设置 DataSource 属性时无法修改项目集合。

标签: c#sql

解决方案


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");
     }
}

这将起作用


推荐阅读