You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# List<itemgridvenda>元素删除失败及表格更新方案咨询

解决DataGridView双击删除List对应元素的问题

问题出在你用Remove(new itemgridvenda(...))的方式——List的Remove方法默认匹配的是对象引用(值类型匹配值相等),你新建的实例和List中存储的不是同一个引用,所以无法匹配到要删除的元素。

给你两种简便且可靠的实现方式:

方式一:通过行索引删除(适用于索引与List顺序完全一致的场景)

直接利用选中行的索引,调用RemoveAt方法删除List中对应位置的元素:

private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
    if (dataGridView1.SelectedRows.Count == 0) return;

    int targetIndex = dataGridView1.SelectedRows[0].Index;
    // 移除List中对应索引的元素
    yourItemList.RemoveAt(targetIndex);
    // 重新绑定数据源以更新表格
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = yourItemList;
}

方式二:直接获取绑定的实体删除(更可靠,适配排序/过滤场景)

直接提取选中行绑定的itemgridvenda实例,用Remove方法删除:

private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
    if (dataGridView1.CurrentRow?.DataBoundItem is not itemgridvenda targetItem) return;

    // 直接移除匹配的实体引用
    yourItemList.Remove(targetItem);
    // 重新绑定数据源更新表格
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = yourItemList;
}

补充说明

  • 之所以要先把DataSource设为null再重新赋值,是因为List<T>没有实现INotifyCollectionChanged接口,直接修改List后DataGridView不会自动感知到变化,这种操作能强制触发重新绑定刷新显示。
  • 如果希望更优雅的自动刷新,可以考虑把List<T>替换为BindingList<T>,它会自动通知DataGridView更新,不需要手动重置数据源。

内容的提问来源于stack exchange,提问作者Luis Antonio Marcelino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:01:03