Highlighting Multiple Search Keywords in ASP.NET

The Entire Code
[C#]

<%@ Page Language="C#" Debug="False" Strict="True" Explicit="True" Buffer="True"%>
<%@ Import Namespace="System" %>

<html>
<head>
<title>Highlighting Multiple Search Keywords in .NET</title>
</head>

<style type="text/css">
.highlight {text-decoration:none; font-weight:bold; color:black; background:yellow;}
</style>

<body bgcolor="#FFFFFF" topmargin="0" marginheight="0" onLoad="document.forms[0].keywords.focus();">

<script language="C#" runat="server">

    void Page_Load(Object Source, EventArgs E)
    {

        LabelTxt.Text = "This sample text is used to demonstrate multiple keyword highlighting in .NET.
 Simply type in any word or words found within this sample text and hit the submit button to highlight the searched words.
 Also, it doesn't matter how many you enter.";

    }

    public string Highlight(string Search_Str, string InputTxt)
    {

        // Setup the regular expression and add the Or operator.
        Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase)

        // Highlight keywords by calling the delegate each time a keyword is found.
        return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));

        // Set the RegExp to null.
        RegExp = null;

    }

    public string ReplaceKeyWords(Match m)
    {

        return "<span>" + m.Value + "</span>";

    }

</script>

<H3>Highlighting Multiple Search Keywords in .NET</H3><BR>

<form runat="server" method="post">

    <asp:TextBox id="keywords" runat="server"/>
    <asp:Button id="button" Text="Submit" runat="server" /><br><br>
    <asp:Label id="LabelTxt" runat="server"/>

</form>

<%= Highlight(keywords.Text, LabelTxt.Text)%>

</body>
</html>

Highlighting Multiple Keywords

To begin, the Highlight() function here, as in my earlier article, still uses Regular Expressions. In this example, I’ve added a search textbox, a submit button and a label containing some arbitrary sample text that will be searched, by calling and Response.Writing the Highlight() function, and return us our results.

<%= Highlight(keywords.Text, LabelTxt.Text)%>

The Highlight() function, in this example, accepts only two parameters: Search_Str – which are the words to be searched for, and InputTxt – the text to be searched.

public string Highlight(string Search_Str, string InputTxt) {}

Thus, in order to accommodate multiple word searching, we’ll need the regular expression "Or" character operator which is represented by a pipe symbol “|” or vertical bar, to be placed between each word entered in the search box. For example, entering the text “sample multiple text any ” in the search box would call the highlight function, and replace all empty spaces in between each word with a pipe symbol and end up looking like this “sample|multiple|text|any”.

Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegExOptions.IgnoreCase);

Once this occurs, our search terms are ready to be evaluated and processed by our Highlight function’s MatchEvaluator Delegate that is called into operation every time the certain keyword string is found within our searchable text, and replaces the matched keyword with the result of the called delegate function, as listed below.

return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));

Accordingly, the called delegate function ReplaceKeyWords() listed below grabs the value of the regular expression match (m.Value), wraps the highlight style sheet around it, and returns it back to our Highlight() function that replaces the matched keyword within the searchable text.

public string ReplaceKeyWords(Match m)
{

    return "<span>" + m.Value + "</span>";

}

So as a result, in example, by entering the terms “sample multiple text any ” in the search box, and hitting submit, the Highlight() function would search the paragraph below.

This sample text is used to demonstrate multiple keyword highlighting in .NET. Simply type in any word or words found within this sample text and hit the submit button to highlight the searched words. Also, it doesn't matter how many you enter.

And return it back looking like so:

This sampletext is used to demonstrate multiple keyword highlighting in .NET. Simply type in any word or words found within this sample text and hit the submit button to highlight the searched words. Also, it doesn't matter how many you enter.

Word Boundaries

One quick note, the regular expression object instantiated above will match the keywords anywhere in the text. In the example above notice how we were looking for the word “any”, but the word “many” got highlighted as well, and this is the magic of regular expressions. However, there are instances when this ambiguity is unnecessary. So to circumvent this type of behavior, simply replace the Highlight function’s RegEx object with the appropriate one listed below.

[C#]

Regex RegExp = new Regex("\\b" + Search_Str.Replace(" ", "\\b|\\b").Trim() + "\\b", RegexOptions.IgnoreCase);

[VB]

Dim RegExp As Regex = New Regex("\b" & Search_Str.Replace (" ", "\b|\b").Trim() & "\b", RegExOptions.IgnoreCase)

The “\b” added above is one of the few Atomic Zero-Width Assertion metacharacters that allows you the flexibility in limiting the results, for a more precise match. Also notice the “RegexOptions” Enumeration is case sensitive in C#.

The DataGrid WebControl

In addition, as in my previous article, the aforementioned techniques could again be applied to a DataGrid control with ease and allow for a more powerfully featured DataGrid. Implementing this is easily done by simply wrapping the Highlight() function around any data column you wish to search and provide the search keywords, as shown below, and that’s it. You’ll now end up with that column displaying your search words, but highlighted now.

<asp:DataGrid runat="server" id="SearchResults" AutoGenerateColumns="False">
 <Columns>
  <asp:TemplateColumn>
   <ItemTemplate>
   <%# Highlight(KeyWords, DataBinder.Eval(Container.DataItem, "Data column to be searched"))) %>
   </ItemTemplate>
  </asp:TemplateColumn>
 </Columns>
</asp:DataGrid>

Conclusion

There are many different Regular Expression Language Elements that can be customized to modify, create and parse all kinds of strings. All in all, I hope this was a useful read, where you’re now able to add this functionality to your projects and display more informative and detailed results to your user.

Until next time. Happy .NETing </>

(Source: http://totaldevpro.com/blogs/tutorials/pages/highlighting-multiple-search-keywords-in-asp-net.aspx)

Related topics: http://code.google.com/p/subversionreports/source/browse/trunk/Utilities/SyntaxHighlight.cs?r=95

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: