【发布时间】:2014-10-02 09:05:30
【问题描述】:
这方面有很多问题,但没有一个能解决我的问题。我有一个 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”,它会突出显示该单词的所有实例,但如果我搜索“Claims”,它只会突出显示带有大写“C”的单词。任何帮助表示赞赏
【问题讨论】:
-
我想指出的是,即使在修复了区分大小写的
Contains问题之后,如果您搜索,您的代码仍将 (1) 将x的实例替换为XX,以及 (2) 如果您搜索.,请将所有内容替换为.。 -
是的,现在就遇到了。我在想我必须获取搜索项的长度,在单元格中找到索引,然后使用这些变量将在单元格中找到的文本复制到一个新变量中,以便维护案例
-
对于 (1),如果将
"<span style='background-color:yellow'>" + text + "</span>"切换为"<span style='background-color:yellow'>$0</span>",$0会告诉正则表达式在替换中使用它匹配的文本。对于 (2),您可以在输入上使用 `Regex.Escape1。
标签: c# asp.net regex replace ignore-case