c# - 使用窗口窗体中的按钮从列表框中删除所选项目

标签 c# sql

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

当前代码:

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/

相关文章:

c++ - SQLite TEXT CAST to INTEGER or REAL in C++ Does too much

c# - XslCompiledTransform和自定义XmlUrlResolver:“具有相同键的条目已存在”

c# - 使用 DotNetZip 从 zip 文件中提取特定文件夹

c# - Outlook 插件在离线模式下访问交换收件人?

mysql - 子查询返回超过1个值如何解决?

mysql - 如何删除MySQL中的所有事件

mysql - 从 CSV 导入时 PHPMYADMIN 权限被拒绝

c# - Async/Await 或 Task.Run 在控制台应用程序/Windows 服务中

c# - 将 Linq 查询表达式转换为点符号

mysql - 试图获取名字和姓氏