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

C#中DataGrid刷新或点击按钮时如何将垂直滚动条自动移动到顶部

DataGrid加载数据后滚动到顶部的实现方案

以下分别给出WPF和WinForms两个常用平台的实现代码:

WPF 平台(DataGrid控件)

方法1:直接调用滚动方法(适合有后台代码的场景)

在数据加载完成的逻辑、或者按钮点击事件中添加如下代码即可:

// 最简写法:滚动到第一行,适配绝大多数场景
if (dataGrid.Items.Count > 0)
{
    dataGrid.ScrollIntoView(dataGrid.Items[0]);
}

如果需要精确滚动到控件最顶部,可先获取DataGrid内部的ScrollViewer对象再调用滚动方法:

// 先添加辅助方法获取控件内的ScrollViewer
private static T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default;
    int childCount = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childCount; i++)
    {
        Visual currentChild = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = currentChild as T ?? GetVisualChild<T>(currentChild);
        if (child != null) break;
    }
    return child;
}

// 调用滚动到顶部
var scrollViewer = GetVisualChild<ScrollViewer>(dataGrid);
scrollViewer?.ScrollToTop();

方法2:MVVM适配方案

如果使用MVVM模式不想写后台代码,可以自定义附加属性,绑定视图模型中的布尔标识,数据更新后修改标识值即可自动触发滚动。

WinForms 平台(DataGridView控件)

WinForms中对应控件为DataGridView,滚动到顶部代码如下:

// 按钮点击/数据加载完成时调用
if (dataGridView1.Rows.Count > 0)
{
    dataGridView1.FirstDisplayedScrollingRowIndex = 0;
}

如果需要每次刷新数据后自动滚动,把上述代码放到DataBindingComplete事件中即可:

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    if (dataGridView1.Rows.Count > 0)
    {
        dataGridView1.FirstDisplayedScrollingRowIndex = 0;
    }
}

效果示意图:
DataGrid刷新时自动上移垂直滚动条

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:24:05