AJAX Search & Highlight Results in GridView

ASP.NET Gridview is a very powerful control that can display content with options such as sorting and paging. One more feature that a gridview often requires when it contains large volume of data, is 'Searching'. For example, when a manager goes through a gridview that displays employee information and interested only on the information about the employee he is supervising, it will be very easy for him to find that particular record if he had a search box enabled on the employee name column of the gridview. In this post, I am going to explain how to implement asynchronous searching and highlighting the search terms in a gridview based on any one column in the gridview. By asynchronous searching I mean, updating the grid view with the search results without reloading the whole page. After you understand the basic concept of how to implement this, you can also extend the requirement by making the gridview searchable on multiple columns of it.


1. For this example I have used a mysql table named as "employee" with the following structure,

+-------------+-------------+| Field       | Type        |+-------------+-------------+| id          | int(11)     | | name        | varchar(20) || designation | varchar(20) || salary      | varchar(20) |+-------------+-------------+

Create a table with the above structure. This is required because we are going to enable search on the 'name' column of this table.

2. Clear the Html content in your .aspx page. Copy and paste the below code instead, 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>AJAX Search & Highlight in GridView</title>
<style type="text/css">
<form id="form1" runat="server">
    <h1>AJAX Search & Highlight in GridView</h1>
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <asp:Label ID="lblAlert" runat="server" Visible="false" Text="There are no results matching your search input. Please try again with different input"></asp:Label>
                <asp:GridView ID="grdToSearch" runat="server"
                    BackColor="white" BorderColor="Aqua"
                    AutoGenerateColumns="false" ShowFooter="true"
                    <FooterStyle BackColor="DarkOrange"
                    ForeColor="AntiqueWhite" />
                    <PagerStyle BackColor="#99CCCC"
                    ForeColor="#003399" HorizontalAlign="Left" />
                    <HeaderStyle BackColor="DarkOrange"
                    Font-Bold="True" ForeColor="White" />

                   <asp:BoundField DataField="id"
                         HeaderText="ID" />
                    <asp:TemplateField HeaderText="Name">
                    <asp:Label ID="lblFIrstName" runat="server" Text='<%# Highlight(Eval("name").ToString()) %>'>
                    <asp:TextBox ID="txtSearch" runat="server"
                    <asp:Button ID="btnSearch"
                                runat="server" Text="Search"
                                Width="60px" />
                    <asp:Button ID="btnBack"
                                runat="server" Text="Back" Visible="false"
                                Width="60px" />
                      <asp:BoundField DataField="designation"
                         HeaderText="Designation" />
                          <asp:BoundField DataField="salary"
                         HeaderText="Salary" />
    <asp:UpdateProgress ID="UpdateProgress1" runat="server">
            <br />
        <img src="Images/ajax-loading.gif" alt="Searching.. Please wait!"/>

In the above html code, I have added style element to add some css for highlighting the search terms in the search result. 

A ScriptManager control and UpdatePanel control is added for implementing AJAX functionality to the search implementation. Note that grid view is placed inside the UpdatePanel control to ensure that everytime when the user clicks in search button, only the gridview gets reloaded and not the whole page. If you are new to AJAX and for a basic understanding of how AJAX works in ASP.NET, please see this.

In the Grid View, 

  • There is an alert label that is used to display warning message whenever the grid view date does not have any match for the search terms.
  • A footer template that has the search box typically a text box, a search button, that triggers the row_command event of the gridview whenever it is clicked and a back button which helps users to get back to the original result ( hidden initially on page load and displayed only when search results are displayed).
  • An Item template that displays value for Name column as labels. Whenever a value is displayed in the name column it checks for value in the search text box to highlight search terms if present.
Finally, an UpdateProgress control to display the progress of search operation. 

3. In the code-behind page, add the following namespaces. 

using System.Data;
using System.Text.RegularExpressions;

4. Copy and paste the below code inside the code-behind file,
protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
                // Load gridview with data on page load


        private DataTable GetRecords()
                //Fetch data from mysql database
                MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;password=priya123;database=test; pooling=false;");
                string cmd = "select * from employee";                
                MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmd,conn);
                DataSet objDs = new DataSet();
                return objDs.Tables[0];
            catch (MySqlException ex)
                return null;

        private void BindGrid()
            //Fetch data from mysql database
            DataTable dt = GetRecords();
            //Bind the fetched data to gridview
            grdToSearch.DataSource = dt;

        private void SearchText(string strSearchText)
            lblAlert.Visible = false;
            DataTable dt = GetRecords();
            DataView dv = new DataView(dt);
            string SearchExpression = null;
            if (!String.IsNullOrEmpty(strSearchText))
                SearchExpression = string.Format("{0} '%{1}%'",
                grdToSearch.SortExpression, strSearchText);

            dv.RowFilter = "name like" + SearchExpression;
            if (dv.Count > 0)
                grdToSearch.DataSource = dv;
                // Enable button that allow users to get back to the main gridview
                Button backbutton = (Button)grdToSearch.FooterRow.FindControl("btnBack");
                backbutton.Visible = true;
                //Display alert message when there are no matching search results
                lblAlert.Visible = true;

        protected void grdToSearch_RowCommand(object sender, GridViewCommandEventArgs e)
            if (e.CommandName == "Search")
                TextBox txtGrid = (TextBox)grdToSearch.FooterRow.FindControl("txtSearch");
            else if (e.CommandName == "Back")

        public string Highlight(string InputTxt)
            GridViewRow gvr = grdToSearch.FooterRow;
            if (gvr != null)
                TextBox txtExample = (TextBox)grdToSearch.FooterRow.FindControl("txtSearch");

                if (txtExample.Text != null)
                    string strSearch = txtExample.Text;
                    // Setup the regular expression 

                    Regex RegExp = new Regex(strSearch.Replace(" ", "|").Trim(),

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

                    return InputTxt;
                return InputTxt;

        public string ReplaceKeyWords(Match m)
            return "" + m.Value + "";

Order of execution and explanation of the above code:

  • Initially, we are loading the grid view with data in the Page_Load event.
  • Whenever an user clicks on the search button in the grid view, rowcommand event of the gridview is triggered.
  • RowCommand event checks for the CommandName, which is "Search" in case if the user clicks the search button and then SearchText() method is called.
  • SearchText() method is responsible for the actual searching - It uses RowFilter to filter results based on the column "name".
  •  Highlight() method is responsible for text highlighting. It matches the value in the search text box which each record in the gridview using regular expression functionality and highlights the results in yellow color making use of the css class used in the .aspx page.

5. That is all you have to do to implement search in grid view and highlighting of search terms in the results. Run the application and look for similar output as shown below.

Ajax Search in Grid View

AJAX Search in Gridview

ajax search in grid view

Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.Thanks for reading!!


advertise here


Search 158812643431024953

Post a Comment

  1. Compiler Error Message: BC30456: 'grdToSearch_RowCommand' is not a member of 'ASP.default_aspx'.

    1. Hi,

      Are you sure you added grdToSearch_RowCommand event to your code-behind file? Also please make sure whether the event name in the code behind file and the declaration OnRowCommand="eventname" matches.

      Hope this helps!



Currency Converter

Built using AngularJS and ASP.NET Web API