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

如何实现DataGridView搜索RAL或存储位置后自动显示选中行?

解决DataGridView选中行自动滚动显示的问题

要让选中的行自动滚动到可视区域,只需在设置row.Selected = true后添加一行定位代码即可,以下是两种常用实现方式:

方法1:通过FirstDisplayedScrollingRowIndex定位

直接指定目标行的索引,DataGridView会自动滚动到该行:

string sucheRAL = txt_in_RAL.Text;
string sucheLagerort = txt_in_Lagerort.Text;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        row.Selected = false;

        // 匹配RAL的情况
        if (row.Cells["RAL"].Value != null && row.Cells["RAL"].Value.ToString().Equals(sucheRAL))
        {
            row.Selected = true;
            // 自动滚动到该行
            dataGridView1.FirstDisplayedScrollingRowIndex = row.Index;
            break;
        }

        // 匹配Lagerort的情况
        if (row.Cells["Lagerort"].Value != null && row.Cells["Lagerort"].Value.ToString().Equals(sucheLagerort))
        {
            row.Selected = true;
            // 自动滚动到该行
            dataGridView1.FirstDisplayedScrollingRowIndex = row.Index;
            break;
        }
    }
}
catch (Exception ex)
{
    // 可根据需求添加异常提示逻辑
    MessageBox.Show($"搜索异常:{ex.Message}");
}

方法2:通过设置CurrentCell定位

将目标行的任意单元格设为当前单元格,DataGridView会自动滚动到该行:
把方法1中的dataGridView1.FirstDisplayedScrollingRowIndex = row.Index;替换为:

dataGridView1.CurrentCell = row.Cells[0]; // 选择该行第一个单元格作为当前单元格

额外逻辑优化提示

原代码存在一处逻辑瑕疵:每个循环中若RAL匹配就直接break,导致Lagerort的判断仅在RAL不匹配时才会执行;如果需要支持RAL和Lagerort的多条件/模糊搜索,需调整break的触发时机。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:57:28