There are lots of questions around this but none solve my problem. I have a SQL server database as the datasource, an input text box and a search button. When the text is entered and the search button is pressed, a dropdown list of rows that contain the searched text is displayed. The user selects the row they want to look at and that information is displayed in a gridview. (1 row returned)
I want the searched text to be highlighted. This is what I have and it should work but I cant figure out why it doesn't:
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;
}
}
}
The above code is inside the event for the dropdown selected item changed. If I searched for "claims", it will highlight all instances of that word but if I searched for "Claims", it only highlights words with the capital "C". Any help appreciated
Containsissue, your code will still (1) replace instances ofxwithXif you search forX, and (2) replace everything with.if you search for.."<span style='background-color:yellow'>" + text + "</span>"to"<span style='background-color:yellow'>$0</span>", the$0tells the regular expression to use the text it matched in the replacement. For (2), you can use `Regex.Escape1 on the input.