How do I highlight search text results in ASP.NET search page? In a FAQ page, I have a search functionality. When I make a find on the search text, I want to highlight in Red, all the instances of the text searched for. This article shows how to accomplish this functionality.
The code in Figure 1 shows the search code. First, it calls a DataHelper (DAL) search method to find any matches in the database table for the search text. If any matches are found, it uses a Regex.Replace to wrap each instance of the search text in an HTML SPAN tag which highlights the finds.
Figure 1 - Search FAQs in DataBase and Highlight Results
| DataHelper hlpr = new DataHelper(AppWrapper.DBConnection); DataTable dt = hlpr.SearchFAQs(searchString); if (dt.Rows.Count > 0) { StringBuilder sb = new StringBuilder(); foreach ( DataRow dr in dt.Rows) { string coloredSearchString = string.Format("<span style=\"background-color:Yellow\">{0}</span>", searchString); string question = NullableTypeHelper.NullSafeToString(dr["Question"]); string answer = NullableTypeHelper.NullSafeToString(dr["Answer"]); // create regex replace pattern and make it safe by escaping it string searchPattern = string.Format("(?<find>{0})", searchString); string replacePattern = "<span style=\"background-color:Red\">${find}</span>"; // color the searched for text yellow in question and answer question = Regex.Replace(question, searchPattern, replacePattern, RegexOptions.IgnoreCase); answer = Regex.Replace(answer, searchPattern, replacePattern, RegexOptions.IgnoreCase); string concat = string.Format("<li>{0}<br />{1}<br /><br />", question, answer); sb.Append(concat); } // foreach litSearchAnswers.Text=sb.ToString(); } // if else { litSearchAnswers.Text = GetLocalResourceObject("MsgNotFound").ToString(); } // else |
| What steps do I follow before sending a message to my contact list? 1. Set up your Business account. 2. Create a contact list of people who will receive your message(s). |
| What steps do I follow before sending a message to my contact/member <span style="background-color:Red">list</span>?<br />1. Set up your Business account.<br>2. Create a contact <span style="background-color:Red">list</span> of people who will receive your message(s).<BR> |
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |