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

DataGridView不区分大小写搜索实现问题及代码求助

搞定DataGridView不区分大小写的文本搜索

嘿,我懂你的需求——现在的搜索会区分大小写,想让它匹配“Modele”的时候不管是大写小写都能命中对吧?

你原来的代码用的是默认的string.Contains()方法,这个方法默认是区分大小写的,咱们只需要调整一下匹配规则就行。这里给你两种靠谱的方案:

方案一:使用StringComparison参数(推荐)

这种方式不仅不区分大小写,还能避免一些特殊字符的匹配问题,性能也更优:

private void textBox_model_TextChanged(object sender, EventArgs e)
{
    string searchValue = textBox_model.Text;
    for (int u = 0; u < dataGridView_Articles.RowCount; u++)
    {
        // 先判断单元格值是否为空,防止空引用异常
        if (dataGridView_Articles.Rows[u].Cells[5].Value != null)
        {
            string cellContent = dataGridView_Articles.Rows[u].Cells[5].Value.ToString();
            // 用OrdinalIgnoreCase实现不区分大小写的包含匹配
            if (cellContent.Contains(searchValue, StringComparison.OrdinalIgnoreCase))
            {
                dataGridView_Articles.Rows[u].Visible = true; // 匹配到就显示行
            }
            else
            {
                dataGridView_Articles.Rows[u].Visible = false; // 没匹配到就隐藏
            }
        }
        else
        {
            dataGridView_Articles.Rows[u].Visible = false; // 空单元格直接隐藏
        }
    }
}

方案二:统一转成小写(或大写)再比较

如果你不需要处理特殊语言字符,这种方式也简单直接:

private void textBox_model_TextChanged(object sender, EventArgs e)
{
    string searchValue = textBox_model.Text.ToLower();
    for (int u = 0; u < dataGridView_Articles.RowCount; u++)
    {
        if (dataGridView_Articles.Rows[u].Cells[5].Value != null)
        {
            string cellContent = dataGridView_Articles.Rows[u].Cells[5].Value.ToString().ToLower();
            if (cellContent.Contains(searchValue))
            {
                dataGridView_Articles.Rows[u].Visible = true;
            }
            else
            {
                dataGridView_Articles.Rows[u].Visible = false;
            }
        }
        else
        {
            dataGridView_Articles.Rows[u].Visible = false;
        }
    }
}

重点提醒

一定要加上单元格空值判断!不然如果某行的第5列是空的,调用ToString()的时候会直接抛出空引用异常,程序就崩啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:27:11