Tuesday, December 2, 2008

Search Records In GridView And Highlight Results Using AJAX ASP.NET


In this example i am searching records of gridview and highlighting the results based on search criteria user enter in textbox .

This example is using AJAX and C# asp.NET


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Grid Search example</title>
<style type="text/css">
.highlight {
text-decoration:none; font-weight:bold;
color:black; background:yellow;}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server" />

<div>
Enter first name to search:
</div>
<div>
<asp:TextBox ID="txtSearch" runat="server"
AutoPostBack="True"
OnTextChanged="txtSearch_TextChanged">
</asp:TextBox>&nbsp;
</div>
<div>
<asp:UpdatePanel ID="UpdatePanel1"
runat="server">
<ContentTemplate>
<asp:GridView ID="grdSearch"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName"
runat="server"
Text='<%# Highlight(Eval("FirstName").ToString()) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server"
Text='<%#(Eval("LastName")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server"
Text='<%#(Eval("Location")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch"
EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

</div>

</form>
</body>
</html>

And it code behind
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.Data.SqlClient;
using System.Text.RegularExpressions;

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

private DataTable GetRecords()
{
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
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();
dAdapter.Fill(objDs);
return objDs.Tables[0];

}
private void BindGrid()
{
DataTable dt = GetRecords();
if (dt.Rows.Count > 0)
{
grdSearch.DataSource = dt;
grdSearch.DataBind();
}
}
private void SearchText()
{
DataTable dt = GetRecords();
DataView dv = new DataView(dt);
string SearchExpression = null;
if (!String.IsNullOrEmpty(txtSearch.Text))
{
SearchExpression = string.Format("{0} '%{1}%'",
grdSearch.SortExpression, txtSearch.Text);

}
dv.RowFilter = "FirstName like" + SearchExpression;
grdSearch.DataSource = dv;
grdSearch.DataBind();

}
public string Highlight(string InputTxt)
{
string Search_Str = txtSearch.Text.ToString();
// 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 class=highlight>" + m.Value + "</span>";

}

protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchText();
}
}


Download the sample code



Related Posts:
1. Search within records in GridView with searchbox in footer and highlight results using AJAX and C# ASP.NET
2. User validation across pages using session after login in ASP.NET using C sharp
3. Finding IP address behind Proxy using C# in ASP.NET
www.tips-fb.com
Shout it
Stumble Upon Toolbar
Submit this story to DotNetKicks vote it on WebDevVote.com add to del.icio.us saved by 0 users
Subscribe to Feeds

11 comments:

Anonymous said...

Nice article


Anonymous said...

Thanks your article!


گزارش said...

thanks for the article.it saved me a lot of research for doing such things


Anonymous said...

Very Nice Article. Lot useful in many Scenarios


Mora said...

Great Article !!


Shakti Singh Dulawat said...

This is very nice example mention my you, this is helpful for programming logic.
Thanks
Shakti
www.nextmvp.blogspot.com


Anonymous said...

Very nice example thanx


Anonymous said...

how to do if the gridview is multi-page?


Danish Wadhwa said...

Hey..! Quite convinced with you post.

Actually i am new to ASP and if the same thing i want to do with Access Database...What are the few changes which i have to consider..!


Danish said...

Hello Nice Post..!
Can you help me to resolve this error and i am using an Access Database in my application..!
Will be waiting for you reply.

ERROR: Type or namespace definition, or end-of-file expected

Danish Wadhwa
You can reply me on my Email
me@danishwadhwa.com


Anonymous said...

it is very usefull article, but from my point of view this will be more userfriendly if there will no need to press enter button.
Thanking you


Comments

.NET Resources

Find More Articles


Subscribe To Feeds

Subscribe by E-mail

Enter your email address:

Delivered by FeedBurner


Subscribe in your favorite reader

Proper Display Of Site

This site is best viewed with || You may get errors in proper display of this site if using Internet explorer