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

如何实现两个DataGridView的垂直滚动条同步滚动

两个DataGridView垂直滚动同步实现方案

以下是WinForm环境下的完整实现,适配拖动滚动条、鼠标滚轮两种滚动操作:


前置准备

首先在窗体类中声明同步锁变量,避免两个控件滚动事件循环触发:

// 同步锁标记,防止滚动事件互相触发死循环
private bool isSyncingScroll = false;

核心事件处理逻辑

1. 滚动事件同步方法

统一处理两个DataGridView的Scroll事件,同步垂直滚动位置:

private void DataGridView_Scroll(object sender, ScrollEventArgs e)
{
    if (isSyncingScroll || e.ScrollOrientation != ScrollOrientation.VerticalScroll)
    {
        return;
    }

    DataGridView sourceDgv = sender as DataGridView;
    DataGridView targetDgv = sourceDgv == dataGridView1 ? dataGridView2 : dataGridView1;

    isSyncingScroll = true;
    // 直接同步首行显示索引,因两个控件行高、行数完全一致,可保证完全对齐
    targetDgv.FirstDisplayedScrollingRowIndex = sourceDgv.FirstDisplayedScrollingRowIndex;
    isSyncingScroll = false;
}

2. 鼠标滚轮事件同步方法

单独处理MouseWheel事件,覆盖部分场景下滚轮操作不触发Scroll事件的问题:

private void DataGridView_MouseWheel(object sender, MouseEventArgs e)
{
    if (isSyncingScroll)
    {
        return;
    }

    DataGridView sourceDgv = sender as DataGridView;
    DataGridView targetDgv = sourceDgv == dataGridView1 ? dataGridView2 : dataGridView1;

    isSyncingScroll = true;
    targetDgv.FirstDisplayedScrollingRowIndex = sourceDgv.FirstDisplayedScrollingRowIndex;
    isSyncingScroll = false;
}

事件绑定

在窗体初始化逻辑(构造函数/Load事件)中为两个控件绑定对应事件:

// 绑定滚动事件
dataGridView1.Scroll += DataGridView_Scroll;
dataGridView2.Scroll += DataGridView_Scroll;
// 绑定鼠标滚轮事件
dataGridView1.MouseWheel += DataGridView_MouseWheel;
dataGridView2.MouseWheel += DataGridView_MouseWheel;

注意事项

  • 该方案依赖你提到的「两个控件行数始终相同、对应行高完全一致」的前提,无需额外计算滚动条像素偏移即可实现精准对齐
  • 若需要同时同步水平滚动,仅需在Scroll事件中增加水平滚动方向的判断,同步两个控件的FirstDisplayedScrollingColumnIndex属性即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:15:07