c#.Regx.replace忽略不起作用的情况

本文关键字:不起作用 情况 Regx replace | 更新日期: 2023-09-27 18:25:28

这方面有很多问题,但没有一个能解决我的问题。我有一个SQL服务器数据库作为数据源,一个输入文本框和一个搜索按钮。当输入文本并按下搜索按钮时,将显示包含搜索文本的行的下拉列表。用户选择要查看的行,该信息将显示在网格视图中。(返回1行)

我希望突出显示搜索到的文本。这就是我所拥有的,它应该起作用,但我不明白为什么它不起作用:

foreach (GridViewRow row in searchTextGridView2.Rows)
        {
            string text = searchText_txt.Text; //Text that was entered in the search text field
            int length = searchTextGridView2.Columns.Count; //Number of Columns on the grid
            for (int i = 0; i < length; i++) //loop through each column
            {
                string newText = row.Cells[i].Text.ToString(); //Get the text in the cell
                if (newText.Contains(text)) //If the cell text contains the search text then do this
                {
                    string highlight = "<span style='background-color:yellow'>" + text + "</span>";
                    string replacedText = Regex.Replace(newText, text, highlight, RegexOptions.IgnoreCase);
                    row.Cells[i].Text = replacedText;
                }
            }
        }

上面的代码在已更改的下拉选择项的事件中。如果我搜索"claims",它会突出显示该单词的所有实例,但如果搜索"clamps",则只突出显示大写"C"的单词。感谢的任何帮助

c#.Regx.replace忽略不起作用的情况

您的问题不是来自Replace()方法,而是来自Contains()方法。

每当您在字符串上调用Contains()时,它将执行case-sensitive比较,因此以下行将始终返回false:

"Some Claims".Contains("claims");

为了克服这个问题,你应该使用String.IndexOf(String, Int32)方法:

for (int i = 0; i < length; i++) 
{
    string newText = row.Cells[i].Text.ToString(); 
    if (newText.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0
    {
        string highlight = "<span style='background-color:yellow'>$0</span>";
        string replacedText = Regex.Replace(newText, text, highlight, RegexOptions.IgnoreCase);
        row.Cells[i].Text = replacedText;
    }
}