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

C# 如何在 DataGridView 中实现多列检索查询功能

C# DataGridView 多列检索实现方案

核心改动说明

你原有代码仅匹配产品名称p.pdesc字段,要实现产品名称、品牌名称、分类名称的多列检索,只需在SQL的WHERE条件中用OR关联另外两个字段的匹配规则即可。同时原有代码采用字符串拼接SQL存在SQL注入安全隐患,以下方案同步做了参数化查询优化:

修改后完整代码

public void LoadProducts()
{
    int i = 0;
    dataGridView1.Rows.Clear();
    // 构造带多列匹配的SQL语句,用参数占位符避免注入
    string sql = @"select p.pcode, p.barcode, p.pdesc, b.brand, c.category, p.price1, p.price2, p.qty 
                    from tblproduct as p 
                    inner join tblbrand as b on b.id = p.bid 
                    inner join tblcategory as c on c.id = p.cid 
                    where p.pdesc LIKE @SearchKey 
                        OR b.brand LIKE @SearchKey 
                        OR c.category LIKE @SearchKey 
                    order by p.pdesc";
    cn.Open();
    cm = new SqlCommand(sql, cn);
    // 添加参数,% 匹配规则可按需调整:
    // 前缀匹配(输入关键词开头匹配):txtSearch.Text + "%"
    // 全模糊匹配(关键词任意位置匹配):"%" + txtSearch.Text + "%"
    // 后缀匹配(输入关键词结尾匹配):"%" + txtSearch.Text
    cm.Parameters.AddWithValue("@SearchKey", txtSearch.Text + "%");
    dr = cm.ExecuteReader();
    while (dr.Read())
    {
        i++;
        dataGridView1.Rows.Add(i, dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString(), dr[4].ToString(), dr[5].ToString(), dr[6].ToString(), dr[7].ToString());
    }
    dr.Close();
    cn.Close();
}

可选配置说明

  • 如果需要实现三个字段同时满足检索条件,将OR替换为AND即可
  • 如果需要匹配字段任意位置包含检索关键词,将参数赋值改为"%" + txtSearch.Text + "%"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:27:03