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

WinForms中基于列值定位GridView/DataSet行(仿Delphi Locate功能)

实现类似Delphi TDataSet的Locate功能

需求说明

  • 支持通过指定列值定位DataSet中的特定记录
  • 定位后在GridView中高亮显示该记录
  • 适配DataSet动态更新(插入操作后仍能正常定位)

Delphi 原方法参考

方法定义

DataSet.Locate(String, Variant, [LocateOptions]);

示例代码

// Delphi 示例
Locate('StudentID', StudentIDVal, []); // StudentID 是 DataSet 中的列,StudentIDVal 是要查找的目标值

实现方案(以C# WinForms为例)

1. 核心定位逻辑

直接遍历DataSet当前的行数据,适配动态插入的场景,不依赖缓存:

private DataRow LocateInDataSet(DataSet dataSet, string columnName, object targetValue)
{
    if (dataSet?.Tables.Count == 0) return null;
    
    foreach (DataRow row in dataSet.Tables[0].Rows)
    {
        // 处理空值和类型匹配问题
        if (row[columnName] != DBNull.Value && row[columnName].Equals(targetValue))
        {
            return row;
        }
    }
    return null;
}

2. GridView高亮与定位

找到目标行后,将其滚动到可视区域并高亮:

private void LocateAndHighlightInGridView(DataGridView dataGridView, DataRow targetRow)
{
    if (dataGridView == null || targetRow == null) return;

    // 找到对应的GridView行索引
    var targetGridViewRow = dataGridView.Rows.Cast<DataGridViewRow>()
        .FirstOrDefault(r => r.DataBoundItem is DataRowView drv && drv.Row == targetRow);
    
    if (targetGridViewRow == null) return;

    int rowIndex = targetGridViewRow.Index;
    // 滚动到目标行
    dataGridView.FirstDisplayedScrollingRowIndex = rowIndex;
    // 选中目标行
    dataGridView.Rows[rowIndex].Selected = true;
    // 设置高亮样式
    dataGridView.Rows[rowIndex].DefaultCellStyle.BackColor = Color.LightBlue;
    
    // 清除其他行的高亮
    foreach (DataGridViewRow row in dataGridView.Rows)
    {
        if (row.Index != rowIndex)
        {
            row.DefaultCellStyle.BackColor = dataGridView.DefaultCellStyle.BackColor;
        }
    }
}

3. 调用示例

// 查找StudentID为123的记录并高亮
DataRow foundRow = LocateInDataSet(yourDataSet, "StudentID", 123);
LocateAndHighlightInGridView(yourDataGridView, foundRow);

动态更新适配说明

由于每次定位都是直接遍历DataSet当前的DataTable行数据,无论后续插入多少新记录,下次调用定位方法时都会自动包含最新数据,无需额外维护缓存或监听数据变更事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:52:55