Skip to main content

Highlighting Search Keywords in a DataGrid Web Control


Introduction


In many of the popular search engines (such as Google), when you perform a search the resulting page displays a short text snippet from each search "hit" with each of those search words you had specified in bold type face. Similarly, if you view Google's cached version of a search hit, the word(s) you searched on are highlighted different colors to make them easy to pick out.



This article will examine how to provide such functionality in ASP.NET when using a DataGrid Web control. A DataGrid is an excellent Web control to list search results. Essentially you provide a TextBox Web control into which a user can enter a search query. When the user submits the form, it's posted back and the database is queried for matching records. These returned results can then be databound to the DataGrid, which will show one result per HTML table row. For more information on the DataGrid Web control be sure to read Scott Mitchell's A Thorough Examination of the DataGrid Web Control article series.

Highlighting Selected Words


The first thing you may be wondering is how in the world we're going to highlight a user's search criteria. Rather than delve into the specifics in this article, I will point you to two other excellent articles here on 4Guys that explain these topics. First, take a gander at Richard Lowe's Common Applications of Regular Expressions, which illustrates how to use regular expressions such functionality can easily be incorporated through the use of regular expressions. (You may also wish to check out and this live demo.) As Richard's article shows, highlighting selected words is fairly easy to do with regular expressions. (For more information on regular expressions be sure to check out the Regular Expressions Article Index.)
A second article you should read, if you haven't already, is Scott Mitchell's Customizing DataBinded Output in Templates, which discusses how alter the output of a templated Web control based upon the data in the databound sections of the template.
A good understanding of both of these two articles is an important prerequisite for this article. To accomplish highlighting of search terms in a DataGrid we will need to use the regular expression techniques discussed in Richard's article as well as the techniques for altering the databound output based upon the value of the data, as discussed in Scott's article.

The Code for the DataGrid


Our DataGrid will need to contain a TemplateColumn since we need to be able to alter the search results on the fly (in order to highlight the search terms in the results). Note that you could also accomplish this same output using a DataList or Repeater control; however, using the DataGrid provides certain advantages, such as the ability to easily page and sort the results.
Below you can see the bare minimum needed for the DataGrid output. You can "fancy it up" as you see fit. To learn more about "prettying" up the DataGrid's output be sure to read this article.

<asp:DataGrid runat="server" id="SearchResults" AutoGenerateColumns="False">
  <Columns>
    <asp:TemplateColumn>
      <ItemTemplate>
        <%# Highlight(searchword, DataBinder.Eval(Container.DataItem, "data")), 
                "<span class=highlight>", "</span>") %>
      </ItemTemplate>
    </asp:TemplateColumn>
  </Columns>
</asp:DataGrid>

When the DataGrid is rendered (that is, when its DataBind() method is called), the Highlight function is called for each result. The task for the Highlight is to highlight each instance of the user's search keyword stored in the variable searchword in the above code example. (Note for this to work you will need to create a page-level variable named searchword that is assigned the value of the user's search query when the form is originally posted back. See the live demo to examine how this is done in code.) The Highlight function is defined below:

Function Highlight(Search_Str as String, _
                   InputTxt as String, _
                   StartTag as String, _
                   EndTag as String) As String

  Dim ResultStr As String 
  Return Regex.Replace(InputTxt, "\b(" & Regex.Escape(Search_Str) & ")\b", _
           StartTag & "$1" & EndTag, RegExOptions.IgnoreCase)
End Function
[View a Live Demo!]
Here the Highlight function call accepts four parameters:
  1. Search_Str - This is the word that the user entered for the search string.
  2. InputTxt - The text from the search result "hit".
  3. StartTag - The HTML tag to place before each instance of the word that is to be highlighted.
  4. EndTag - The HTML tag to place after each instance of the word that is to be highlighted.
In the DataGrid code note that the values for StartTag and EndTag chosen were <span class=highlight> and </span>, respectively. This HTML will apply the style of a particular class to the word we wish to highlight. It is vital that somewhere in our ASP.NET page that we add a STYLE HTML tag that defines the highlight class. Feel free to use whatever CSS markup you'd like to in order to have the search word "highlighted." The below CSS will give the highlighted word a yellow background.

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

Conclusion


This article illustrated how to highlight search terms in a DataGrid Web control using regular expressions. There is an accompanying live demo that allows you to search a small database of Woody Allen quotes.
Happy Programming!

Comments

Popular posts from this blog

C# Generic class to parse value - "GenericConverter"

    public class GenericConverter     {         public static T Parse<T>(string sourceValue) where T : IConvertible         {             return (T)Convert.ChangeType(sourceValue, typeof(T));         }         public static T Parse<T>(string sourceValue, IFormatProvider provider) where T : IConvertible         {             return (T)Convert.ChangeType(sourceValue, typeof(T), provider);         }     }     public static class TConverter     {         public static T ChangeType<T>(object value)         {             return (T)ChangeType(typeof(T), value);         }         public static object ChangeType(Type t, object value)         {             TypeConverter tc = TypeDescriptor.GetConverter(t);             return tc.ConvertFrom(value);         }         public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter         {             TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));         }     } ----------------

How to create a countdown timer in jquery

Create a countdown timer in jQuery First we need to include the jQuery library file to the HTML page to perform this task. To do that we need to understand that what exactly a jQuery library fie is ? JQuery library file is the library of JavaScript, which means this file contains the predefined functions of jQuery. We just need to call these functions to perform the task. jQuery functions reduces the lines of code and makes our task easy. As this jQuery library file contains the javascript functions so we need to call the function within <script> </script> tag. Now after including the file, we need to define a variable which will store that for how long you want the timer on the page(c=60) and now the time you set needs to be changed in hours , minutes and seconds using the code “ var hours = parseInt( time / 3600 ) % ;var minutes = parseInt( time / 60 ) % 60; var seconds = time % 60;” Now we need to put the condition if timer got finished (if (t

Tip/Trick: Fix Common SEO Problems Using the URL Rewrite Extension

Search engine optimization (SEO) is important for any publically facing web-site.  A large % of traffic to sites now comes directly from search engines, and improving your site’s search relevancy will lead to more users visiting your site from search engine queries.  This can directly or indirectly increase the money you make through your site. This blog post covers how you can use the free Microsoft  URL Rewrite Extension  to fix a bunch of common SEO problems that your site might have.  It takes less than 15 minutes (and no code changes) to apply 4 simple  URL Rewrite  rules to your site, and in doing so cause search engines to drive more visitors and traffic to your site.  The techniques below work equally well with both ASP.NET Web Forms and ASP.NET MVC based sites.  They also works with all versions of ASP.NET (and even work with non-ASP.NET content). [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at:  twitter.com/scottg