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

Windows Forms中双击DataGridView后ComboBox选中值异常求助

解决WinForms ComboBox无法正确选中DataGridView对应项的问题

我来帮你排查这个问题——你的ComboBox选中异常的根源在于获取目标合同名称的逻辑完全错了,咱们一步步来修正:

问题分析

你在双击事件里新建了BindingSource bs并绑定了刚加载的ContratosTable,这时候bs.Current默认指向数据表的第一行,所以你拿到的_nomeContrato其实是第一个合同的名称,自然ComboBox会选中第一项,根本没用到DataGridView当前行的合同ID。而且用FindString匹配名称也有隐患:如果存在同名合同,会选中第一个匹配项,无法精准定位。

修正方案

我们直接用合同ID(IdContrato)来匹配ComboBox的选项,这是最精准的方式,步骤如下:

1. 先获取DataGridView当前行的目标合同ID

从你的DataGridView当前行中提取关联的IdContrato(注意替换成你实际的列名或索引,用列名更可靠):

// 加空判断,避免双击表头/空行抛出异常
if (concelhos_datagrid.CurrentRow == null) return;

// 提取当前行对应的合同ID(假设你的DataGridView列名是IdContrato,替换成实际列名)
int targetContratoId = Convert.ToInt32(concelhos_datagrid.CurrentRow.Cells["IdContrato"].Value);

2. 正确绑定ComboBox的数据源与成员

确保编辑窗体的ComboBox设置了DisplayMember(显示的名称)和ValueMember(实际关联的ID),这样可以直接通过ID选中项:

private void concelhos_datagrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    // 上面的空判断和ID提取代码...

    // 建议提前加载ContratosTable,不要每次双击都查数据库(优化性能)
    if (ContratosTable == null)
        LoadContratosTable();

    Concelhos_Edit f = new Concelhos_Edit();

    // 给ComboBox绑定数据源并设置成员
    f.cmb_contrato.DataSource = ContratosTable;
    f.cmb_contrato.DisplayMember = "Designacao"; // 显示合同名称
    f.cmb_contrato.ValueMember = "IdContrato";   // 关联合同ID

    // 直接用ID选中对应的项,精准无误差
    f.cmb_contrato.SelectedValue = targetContratoId;

    // 其他TextBox赋值保持不变
    f.txt_id.Text = concelhos_datagrid.CurrentRow.Cells[0].Value.ToString();
    f.txt_sigla.Text = concelhos_datagrid.CurrentRow.Cells[2].Value.ToString();
    f.txt_nome.Text = concelhos_datagrid.CurrentRow.Cells[3].Value.ToString();
    f.txt_codigo.Text = concelhos_datagrid.CurrentRow.Cells[4].Value.ToString();
    f.txt_qservico.Text = concelhos_datagrid.CurrentRow.Cells[5].Value.ToString();
    f.chk_ativo.Checked = (bool)concelhos_datagrid.CurrentRow.Cells[6].Value;

    f.MdiParent = this.MdiParent;
    f.Show();
}

3. 额外优化建议

  • 避免重复查询数据库:把LoadContratosTable()移到窗体的Load事件里,只加载一次,不用每次双击都执行SQL,提升响应速度。
  • 用列名代替索引:比如Cells["IdContrato"]比Cells[1]更安全,后续修改DataGridView列顺序不会导致取值错误。
  • 空值处理:如果单元格可能为空,记得加Convert.IsDBNull判断,避免转换失败抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:29:55