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

如何实现两个DataGridView间指定项搜索及匹配值求和

WinForm 双DataGridView匹配检索+求和实现方案

核心逻辑是先缓存DataGridView2的全量原始数据,读取DataGridView1中勾选启用的搜索规则做数据过滤,过滤结果直接绑定回DataGridView2,同时遍历过滤结果做数值求和。

实现步骤

  • 初始化全局缓存变量
    窗体加载时先把DataGridView2的全量数据存在全局DataTable中,避免多次筛选导致原始数据丢失。
// 窗体级全局缓存,存储DataGridView2的全量未筛选原始数据
private DataTable _dgv2OriginalSource;

private void Form_Load(object sender, EventArgs e)
{
    // 替换为你实际的DataGridView2数据加载逻辑,支持从数据库、接口等来源获取DataTable
    _dgv2OriginalSource = LoadDgv2SourceData();
    DataGridView2.DataSource = _dgv2OriginalSource;

    // 初始化DataGridView1搜索项,列结构固定为:[搜索字段名, 是否启用(复选框), 搜索关键词输入框]
    DataGridView1.Rows.Add("商品编码", false, "");
    DataGridView1.Rows.Add("商品名称", false, "");
}
  • 编写检索+求和逻辑
    支持多条件组合匹配,筛选完成后自动计算指定数值列的总和。
/// <summary>
/// 执行检索,可绑定搜索按钮点击事件、或DataGridView1单元格编辑完成事件实现实时搜索
/// </summary>
private void ExecuteSearch()
{
    List<string> filterExpressions = new List<string>();
    // 遍历DataGridView1读取启用的搜索条件
    foreach (DataGridViewRow ruleRow in DataGridView1.Rows)
    {
        bool isRuleEnabled = Convert.ToBoolean(ruleRow.Cells[1].Value);
        if (!isRuleEnabled) continue;

        string matchField = ruleRow.Cells[0].Value?.ToString().Trim();
        string keyword = ruleRow.Cells[2].Value?.ToString().Trim();
        if (string.IsNullOrWhiteSpace(matchField) || string.IsNullOrWhiteSpace(keyword)) continue;

        // 单引号转义防止过滤语法报错,默认模糊匹配,需要精确匹配把LIKE '%%'改成=即可
        string safeKeyword = keyword.Replace("'", "''");
        filterExpressions.Add($"{matchField} LIKE '%{safeKeyword}%'");
    }

    // 基于缓存的原始数据做过滤
    DataView filteredView = new DataView(_dgv2OriginalSource);
    if (filterExpressions.Count > 0)
    {
        // 多条件默认取交集(AND),需要取并集把" AND "替换为" OR "
        filteredView.RowFilter = string.Join(" AND ", filterExpressions);
    }
    DataTable filteredResult = filteredView.ToTable();

    // 绑定筛选结果到DataGridView2
    DataGridView2.DataSource = filteredResult;

    // 计算匹配条目指定数值列的总和,此处替换为你实际需要求和的列名,比如"金额""库存"
    decimal totalValue = 0;
    foreach (DataRow item in filteredResult.Rows)
    {
        if (decimal.TryParse(item["金额"].ToString(), out decimal num))
        {
            totalValue += num;
        }
    }

    // 求和结果输出,可替换为你需要的展示位置:标签、DataGridView汇总行等
    lbl_SumResult.Text = $"匹配项总金额:{totalValue:N2}";
}
  • 可选配置
    • 实时搜索:把ExecuteSearch()方法绑定到DataGridView1的CellEndEdit事件,用户勾选规则、输入关键词后自动触发检索,无需点击按钮
    • 汇总行展示:设置DataGridView2.AllowUserToAddRows = false,数据绑定完成后手动新增一行,将求和值填入对应数值单元格即可
    • 数值/日期匹配:针对数值、日期类型的搜索字段,可调整过滤表达式为对应类型的比较逻辑,比如$"库存 >= {safeKeyword}"

注意:所有筛选操作必须基于缓存的全量原始数据执行,禁止直接修改DataGridView2已绑定的数据源做过滤,否则多次检索后会出现数据缺失、匹配结果错误的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 15:09:17