Tuesday, November 17, 2009

Highlight Search Keyword in datalist



When you are displaying search result in datalist, if you highlight seach keyword,it will be easy for user user.


Use thisfunction to highlight search term.


protected string HighlightText(string searchWord, string inputText)
    {
        if (searchWord != null && searchWord != "")
        {
            Regex expression = new Regex(searchWord.Replace(" ", "|"), RegexOptions.IgnoreCase);
            return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
        }
        return inputText;
    }

    public string ReplaceKeywords(Match m)
    {

        return  "" + m.Value + "";
      
    }


And add this inside your datalist.
 <%#HighlightText(txtSearch.Text,Eval("YourField").ToString())%>

Now the search term in YourField will be highlighted in bold. you can chang this as you like.

No comments: