Go to DotNetFunda.com
 Online : 1934 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET AJAX > Implementing search in GridView and highlight results

  • Download the OOPS, ASP.NET and ADO.NET Training Videos for FREE, click here.

Submit Article | Articles Home | Search Articles |

Implementing search in GridView and highlight results

 Download source file
 Posted on: 1/8/2009 5:22:39 AM by Amit.jain | Views: 6079 | Category: ASP.NET AJAX | Level: Intermediate | Print Article
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

.NET Training Videos!
Buy online comprehensive training video pack just for $35.00 only, see what's inside it.


Html code for the aspx page is

<%@ 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>Search and highlight Results in Grdiview
</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" />
<asp:UpdatePanel ID="UpdatePanel1"
runat="server">
<ContentTemplate>
<div>
<asp:GridView ID="grdSearch" runat="server"
BackColor="white" BorderColor="Aqua"
AutoGenerateColumns="false" ShowFooter="true"
OnRowCommand="grdSearch_RowCommand">
<FooterStyle BackColor="AliceBlue"
ForeColor="AntiqueWhite" />
<PagerStyle BackColor="#99CCCC"
ForeColor="#003399" HorizontalAlign="Left" />
<HeaderStyle BackColor="#003399"
Font-Bold="True" ForeColor="#CCCCFF" />

<Columns>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFIrstName" runat="server"
Text='<%# Highlight(Eval("FirstName").ToString()) %>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtSearch" runat="server"
Width="70px"></asp:TextBox>
<asp:Button ID="btnSearch"
CommandName="Search"
runat="server" Text="Search"
Width="60px" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="LastName"
HeaderText="LastName" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1"
runat="server">
<ProgressTemplate>
<br />
<img src="Images/ajax.gif"
alt="Searchig" />
</ProgressTemplate>
</asp:UpdateProgress>
</form>
</body>
</html>
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)
{
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();
}
}

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;
grdSearch.DataBind();
}
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)
{
System.Threading.Thread.Sleep(2000);
if (e.CommandName == "Search")
{
TextBox txtGrid =(TextBox)grdSearch.FooterRow.FindControl("txtSearch");
SearchText(txtGrid.Text);
}
}

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(),
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;

}
else
return InputTxt;
}
else
{
return InputTxt;
}
}

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

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


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Interesting?   Share and Bookmark this kick it on DotNetKicks.com


About amiT jaiN

Experience:4 year(s)
Home page:http://csharpdotnetfreak.blogspot.com/
Member since:Friday, December 26, 2008
Level:Starter
Status: [Member]
Biography:
 Latest post(s) from Amit.jain

   ◘ Disabling copy paste in a textbox on aspx page posted on 1/22/2009 8:21:06 AM
   ◘ Creating AutoComplete TextBox in Windows Froms using C# posted on 1/13/2009 6:45:30 AM
   ◘ Implementing autocomplete textbox in gridview using Ajax autocomplete extender posted on 1/11/2009 10:05:43 AM
   ◘ Implementing search in GridView and highlight results posted on 1/8/2009 5:22:39 AM
   ◘ Redirection to Login page after session time out posted on 1/5/2009 7:49:14 AM


Submit Article

About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)