Implementing search in GridView and highlight results

Posted by in ASP.NET AJAX category on for Intermediate level | Views : 51295 red flag
Rating: 5 out of 5  
 1 vote(s)

In this example i am populating gridview by creating Sqlconnection and SqlCommand, i've put a textbox for text to search in footer of gridview using footer template , and the search results are highlighted using regular expression, i m using AJAX for partial postback and update progress template to show search progress

 Download source code for Implementing search in GridView and highlight results

Html code for the aspx page is

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<html xmlns="">
<head runat="server">
<title>Search and highlight Results in Grdiview
<style type="text/css">
.highlight {text-decoration:none; font-weight:bold;
color:black; background:yellow;}
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server" />
<asp:UpdatePanel ID="UpdatePanel1"
<asp:GridView ID="grdSearch" runat="server"
BackColor="white" BorderColor="Aqua"
AutoGenerateColumns="false" ShowFooter="true"
<FooterStyle BackColor="AliceBlue"
ForeColor="AntiqueWhite" />
<PagerStyle BackColor="#99CCCC"
ForeColor="#003399" HorizontalAlign="Left" />
<HeaderStyle BackColor="#003399"
Font-Bold="True" ForeColor="#CCCCFF" />

<asp:TemplateField HeaderText="FirstName">
<asp:Label ID="lblFIrstName" runat="server"
Text='<%# Highlight(Eval("FirstName").ToString()) %>'>
<asp:TextBox ID="txtSearch" runat="server"
<asp:Button ID="btnSearch"
runat="server" Text="Search"
Width="60px" />
<asp:BoundField DataField="LastName"
HeaderText="LastName" />
<asp:UpdateProgress ID="UpdateProgress1"
<br />
<img src="Images/ajax.gif"
alt="Searchig" />
And the code behind first of all i m populating the Grid by making sqlconnection, Sqlcommand and fatching the data from database, than binding the data to grid view at Page_Load event after checking the page is not loading firs time by by checking flag of isPostBack
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
string strConnection = ConfigurationManager.AppSettings["ConnectionString"];
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)

private DataTable GetRecords()
SqlConnection conn = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Employees";
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
DataSet objDs = new DataSet();
return objDs.Tables[0];

private void BindGrid()
DataTable dt = GetRecords();
if (dt.Rows.Count > 0)
grdSearch.DataSource = dt;

Implementing search within GridView records
Now i've written a method to search the text within results of GridView, which user enter in the TextBox to search
private void SearchText(string strSearchText)
DataTable dt = GetRecords();
DataView dv = new DataView(dt);
string SearchExpression = null;
if (!String.IsNullOrEmpty(strSearchText))
SearchExpression = string.Format("{0} '%{1}%'",
grdSearch.SortExpression, strSearchText);

dv.RowFilter = "FirstName like" + SearchExpression;
grdSearch.DataSource = dv;
Next step is to check the command in RowCommand event of grid view,if it is what u've defined in while creating the button in footer of grid by assigning the commandname property, if yes than get the text entered by user in textbox placed in footer of gridview by using findcontrol method and pass this text to the search method written earlier by making a call to that method
protected void grdSearch_RowCommand(object sender, GridViewCommandEventArgs e)
if (e.CommandName == "Search")
TextBox txtGrid =(TextBox)grdSearch.FooterRow.FindControl("txtSearch");

Highlighting Search results
Now to highlight the search text in results i m using regexp and replacing the the words found with highlighted in yellow color
public string Highlight(string InputTxt)
GridViewRow gvr = grdSearch.FooterRow;
if (gvr != null)
TextBox txtExample = (TextBox)grdSearch.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));

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

return InputTxt;
return InputTxt;

public string ReplaceKeyWords(Match m)
return "<span class=highlight>" + m.Value + "</span>";

This is how we can use and implement AJAX to search within displayed records of  GridView and highlight the searched keywords

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: amiT jaiN
Member Level: Starter
Member Status: Member
Member Since: 12/26/2008 7:19:35 AM

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)