Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Search Records In GridView And Highlight Results Using ASP.NET | how to highlight search results in gridview using asp.net

Dec 3, 2011
Introduction:

In this article I will explain how to search records in gridview and highlight search keywords in gridview using asp.net.


Description:

In Previous post I explained clearly about how to filter gridview records with dropdownlist selection. Now I will explain how to implement search functionality for gridview and highlight search keywords in gridview using asp.net. 

Here my requirement is I have a web page that contains Search textbox, button and gridview with some data now I want to display data in gridview whenever user enter text in textbox and hit search button after that I need to highlight that resultant keyword in gridview using asp.net. To implement this first design the table in database and give name UserInfomation

ColumnName
DataType
UserId
Int(set identity property=true)
UserName
varchar(50)
LastName
varchar(50)
Location
varchar(50)

After completion table creation write some of css classes to change the appearance of gridview and design aspx page like this
 

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Highlight the Search Keywords in Gridview </title>
<style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-decoration:none }
.highlight {text-decoration: none;color:black;background:yellow;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="GridviewDiv">
<p>
Enter UserName :
<asp:TextBox ID="txtSearch" runat="server" />&nbsp;&nbsp;
<asp:ImageButton ID="btnSearch" ImageUrl="~/SearchButton.png" runat="server"
Style="top: 5px; position: relative" onclick="btnSearch_Click" />&nbsp;&nbsp;
<asp:ImageButton ID="btnClear" ImageUrl="~/Clearbutton.png" runat="server" Style="top: 5px;
position: relative" onclick="btnClear_Click" /><br />
<br />
</p>
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="true" DataSourceID="dsDetails" Width="540px" PageSize="10" CssClass="Gridview" >
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="lblFirstname" Text='<%# HighlightText(Eval("UserName").ToString()) %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastname" Text='<%# Eval("LastName") %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" Text='<%#Eval("Location") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:SqlDataSource ID="dsDetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>" SelectCommand="select * from UserInformation" FilterExpression="UserName LIKE '%{0}%'">
<FilterParameters>
<asp:ControlParameter Name="UserName" ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
If you observe above code in header section I written css classes by using those we can change the appearance of gridview, highlight the search keyword by changing the background color and written code to bind gridview and used filter expressions to filter gridview based on search text

Now open code behind file and add following namespaces in code behind

C# Code

using System;
using System.Text.RegularExpressions;
using System.Web.UI;
After completion of adding namespaces write the following code

//  Create a String to store our search results
private string SearchString = "";
protected void Page_Load(object sender, EventArgs e)
{

}
public string HighlightText(string InputTxt)
{
string Search_Str = txtSearch.Text;
// 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));
}

public string ReplaceKeyWords(Match m)
{
return ("<span class=highlight>" + m.Value + "</span>");
}
protected void btnSearch_Click(object sender, ImageClickEventArgs e)
{
//  Set the value of the SearchString so it gets
SearchString = txtSearch.Text;
}
protected void btnClear_Click(object sender, ImageClickEventArgs e)
{
//  Simple clean up text to return the Gridview to it's default state
txtSearch.Text = "";
SearchString = "";
gvDetails.DataBind();
}
VB.NET Code

Imports System
Imports System.Text.RegularExpressions
Imports System.Web.UI
Public Class _Default
Inherits System.Web.UI.Page
'  Create a String to store our search results
Private SearchString As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Public Function HighlightText(ByVal InputTxt As String) As String
Dim Search_Str As String = txtSearch.Text
' Setup the regular expression and add the Or operator.
Dim RegExp As Regex = 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(AddressOf ReplaceKeyWords))
End Function

Public Function ReplaceKeyWords(ByVal m As Match) As String
Return ("<span class=highlight>" + m.Value + "</span>")
End Function

Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
'  Set the value of the SearchString so it gets
SearchString = txtSearch.Text
End Sub

Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
'  Simple clean up text to return the Gridview to it's default state
txtSearch.Text = ""
SearchString = ""
gvDetails.DataBind()
End Sub
End Class
Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
Demo

Download sample code attached



If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

38 comments :

pavithra said...

Great work sir, I am searching for this code from long time..thnx

Anonymous said...

Very Easy and useful way for my Difficulty

PP said...

Thanks sir for ur valuable guidenace

Vinoth said...

thank u sir greate work.........,

Anonymous said...

What if your column you're searching for has spaces? How would you return that value?

yasir said...

Very Very Nice Site. Excellent Work Done.

Thanks Team of Aspdotner-suresh.com web

Jatin rana said...

hello sir,
wil u plz make the same project with the help of datareader. i need it in my project

Anonymous said...

Very nice!!! Great work

Mohanbabu said...

superb site.....it very useful site for all ...

Thanks to suresh.

Anonymous said...

Awesome!! Thanks so much for the useful info. :)

BrianK said...

Am i missing something here? Because when i click my search button im not getting anything?

Anonymous said...

I did not get anything either.
Eugene

Anonymous said...

nice post suresh.

kuldeep chouhan said...

how to hight light bound field meand 'Datafield" in gridview

kuldeep chouhan said...

how to hight light bound field meand 'Datafield" in gridview

chetan patil said...

hi sir ....
It is not working
it just display all data from database
and not highlight any row when i am search....

Suresh Dasari said...

@Chetan patil...
Check your code I hope you did mistake in highlight text method.

Anonymous said...

hi sir.....
how to use this article in asp.net with mvc .

please help me

Anonymous said...

owsome thanks bro

Jesse Christian Ramos said...

This is great suresh. Any idea how can i highlight the whole row instead? Thanks in advance.

Anonymous said...

Hi, thanks for sharing this..by the way, how about multiple search text fields?I'm having prob with it.
Thanks

vikalpa said...

Thank you very much for supporting the new programmers. Most of the posting helps me a lot, n' i hope its same with most of others..


Bikalpa Nepal

Tomáš Hájek said...

Simple and useful, thanks!

priyanka bollepalli said...

i want it windows application vb.net can u guys help me out

priyanka bollepalli said...

i want it windows application vb.net can u guys help me out

Asha said...

Hello Sir,
Sir can you please help me i am writing code to search the files in a folder with keyword search if i have 100 doc file in the search textbox if i enter the word java, C# i need to get only those doc file which has java C# in it. i have done little coding but its displaying all files which is there in folder not the.

ANIL BABU Mandla said...

Hi Suresh,
Can tell me example on Gridview
Display two tables data in a single gridview,
Not for all clolumns data some columes only

That tables are PK and FK relation)

(or)
With out relation also
Plz give me example on this

PavanKumar S K said...

Hi Suresh,
Can you help me in scrolling images
using jquery with asp.net and c#

Basu said...

Hello Sir i need this code with Datasource not with Datasourceid can you please show me that i need that urgent my all connection has done with datacourse

Priya said...

OnClicking back button, the highlighted text is not losing its style, the highlighted text still gets displayed.

panda239 said...
This comment has been removed by the author.
panda239 said...






hot to write it using C#???

DIVINE DIGVIJAY said...

if i use two or three textbox to find result then what should i do

SUBASH R said...

SUBASH
Sir, I want to filter rows in grid view using mobile number on text Changed events plz help me

Rahul Upadhyay said...

Great Work ........Found this

Rahul Upadhyay said...

How it will work to search in last name and Location also

Vinayak Deshpande said...

Thanks sir
for guidenace

Sumit said...

Hi,
I took same GridView & one View button. If we clicks on view button, the data in this row should be displayed in respective textbox controls. Is there any way for Row_command event of Gridview ??
Pls help me out...
Thanks in Advanced

Sumit...

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.