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

DataGridView绑定同数据集Combobox修改BuddyID时行值异常同步问题

问题根因
  • 核心触发点为你补充的「两个伙伴元素下拉显示名称完全相同」:DataGridViewComboBoxColumn默认匹配选中项时会优先识别DisplayMember对应的显示文本,找到第一个匹配的项就直接返回对应ValueMember值,不会校验选中项的主键,重名时会出现匹配错误,导致赋值到错误的ID。
  • 下拉列绑定的komponentenBuddyBindingSource与主网格的komponentenBindingSource默认共用同一绑定上下文,修改下拉选中项时会误触发同数据源的行同步逻辑,导致未操作的行BuddyID被连带修改。
修复方案

1. 解决重名匹配错误

在绑定的DataSet对应DataTable中新增计算列,设置表达式为Komponentenname + '(' + Convert(Id, 'System.String') + ')',再将ComboBox列的DisplayMember修改为该新计算列的名称,让下拉显示值可唯一区分不同行,从根源避免重名匹配问题。

2. 切断BindingSource同步关联

在窗体初始化代码中添加以下代码,给下拉绑定的BindingSource设置独立的绑定上下文:

komponentenBuddyBindingSource.BindingContext = new BindingContext();

3. 可选:新增行过滤规则

如果不允许将当前行设置为自身的伙伴,可添加以下代码实现下拉选项排除当前行:

private void dgvKomponenten_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (dgvKomponenten.CurrentCell.OwningColumn == idBuddyDataGridViewTextBoxColumn 
        && e.Control is DataGridViewComboBoxEditingControl)
    {
        int currentRowId = (int)dgvKomponenten.CurrentRow.Cells["Id"].Value;
        komponentenBuddyBindingSource.Filter = $"Id <> {currentRowId}";
    }
}

private void dgvKomponenten_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == idBuddyDataGridViewTextBoxColumn.Index)
    {
        komponentenBuddyBindingSource.Filter = string.Empty;
    }
}

记得把上述两个事件绑定到对应DataGridView的事件上。

内容的提问来源于stack exchange,提问作者UHM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:39:02