0

围绕这个有很多问题,但没有一个能解决我的问题。我有一个 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;
                }
            }
        }

上面的代码在下拉选定项目更改的事件内。如果我搜索“索赔”,它会突出显示该单词的所有实例,但如果我搜索“索赔”,它只会突出显示大写字母“C”的单词。任何帮助表示赞赏

4

1 回答 1

4

你的问题不在于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;
    }
}
于 2014-10-02T09:17:36.643 回答