c# - 使用窗口窗体中的按钮从列表框中删除所选项目
问题描述
我有一个列表框,我想在其中选择和项目,然后按一个按钮从数据库中删除它。我可以很好地编辑和保存,只是不能删除。
当前代码:
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 属性时无法修改项目集合。
解决方案
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");
}
}
这将起作用
推荐阅读
- python - 为什么我的 pandas 代码会引发分配警告并运行缓慢?
- node.js - 在 BigQuery 中写入的云函数(异步函数 ...等待 bigquery ...)因未处理的拒绝/PartialFailureError 而失败?
- javascript - 如何查询 Express.js 中的特定内容?
- r - 如何过滤()包含dplyr中由文本和数字组成的列中的文本的行?
- python - 在再次打开之前关闭 Windows 程序
- angular - 如何使用ngrx中的数组更新状态
- swift - SwiftUI,仅用于容器的阴影
- connection - webRTC多点连接(3个客户端及以上)
- python - 安装和导入底图时出现问题
- c# - 如何制作一个具有 EditForm 的组件并将表单和验证封装在里面?