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

同一窗体多个DataGridView如何实现同一时间仅单个行选中有效

实现方案

可以共用同一个事件处理方法,实现逻辑如下:

第一步:声明全局锁变量

用于避免清除选中操作时反复触发SelectionChanged事件导致死循环,在窗体类中添加如下字段:

private bool _isClearingSelection = false;

第二步:编写共用的事件处理方法

private void dgv_SelectionChanged(object sender, EventArgs e)
{
    // 程序主动清除选中时直接跳过,避免循环触发
    if (_isClearingSelection) return;

    DataGridView currentDgv = sender as DataGridView;
    // 当前控件无选中行时不处理
    if (currentDgv?.SelectedRows.Count == 0) return;

    try
    {
        _isClearingSelection = true;
        // 判断当前触发事件的控件,清除另一个控件的选中状态
        if (currentDgv == dgvA)
        {
            dgvB.ClearSelection();
            dgvB.CurrentCell = null; // 完全取消激活状态,移除虚线焦点框
        }
        else if (currentDgv == dgvB)
        {
            dgvA.ClearSelection();
            dgvA.CurrentCell = null;
        }
    }
    finally
    {
        _isClearingSelection = false;
    }
}

注意将代码中的dgvA、dgvB替换为你窗体上两个DataGridView控件的实际命名

第三步:绑定事件

两种绑定方式二选一即可:

  • 设计器操作:同时选中两个DataGridView控件,在属性面板的事件列表中找到SelectionChanged,选择上面编写的dgv_SelectionChanged方法
  • 代码绑定:在窗体构造函数的InitializeComponent();后添加如下代码:
dgvA.SelectionChanged += dgv_SelectionChanged;
dgvB.SelectionChanged += dgv_SelectionChanged;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:39:03