In this example i am Explaining how to Search Records In GridView And Highlight Results Using Ajax In Asp.Net 2.0,3.5,4.0 based on text entered in textbox.

Add following CSS style in head section of page.
HTML SOURCE
Write following code in code behind
C# CODE
VB.NET

Add following CSS style in head section of page.
1
<style type=
"text/css"
>
2
.highlight
3
{
4
text-decoration:none; font-weight:bold;
5
color:black; background:yellow;
6
}
7
</style>
HTML SOURCE
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
Enter first name to search:
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True"
OnTextChanged="txtSearch_TextChanged"/>
<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()) %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#(Eval("LastName")) %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#(Eval("Location")) %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
Write following code in code behind
C# CODE
01
protected
void
Page_Load(
object
sender, EventArgs e)
02
{
03
if
(!IsPostBack)
04
{
05
BindGrid();
06
}
07
}
08
private
DataTable GetRecords()
09
{
10
SqlConnection conn =
new
SqlConnection(strConnection);
11
conn.Open();
12
SqlCommand cmd =
new
SqlCommand();
13
cmd.Connection = conn;
14
cmd.CommandType = CommandType.Text;
15
cmd.CommandText =
"Select * from Employees"
;
16
SqlDataAdapter dAdapter =
new
SqlDataAdapter();
17
dAdapter.SelectCommand = cmd;
18
DataSet objDs =
new
DataSet();
19
dAdapter.Fill(objDs);
20
return
objDs.Tables[0];
21
22
}
23
private
void
BindGrid()
24
{
25
DataTable dt = GetRecords();
26
if
(dt.Rows.Count > 0)
27
{
28
grdSearch.DataSource = dt;
29
grdSearch.DataBind();
30
}
31
}
32
private
void
SearchText()
33
{
34
DataTable dt = GetRecords();
35
DataView dv =
new
DataView(dt);
36
string
SearchExpression =
null
;
37
if
(!String.IsNullOrEmpty(txtSearch.Text))
38
{
39
SearchExpression =
string
.Format(
"{0} '%{1}%'"
,
40
grdSearch.SortExpression, txtSearch.Text);
41
42
}
43
dv.RowFilter =
"FirstName like"
+ SearchExpression;
44
grdSearch.DataSource = dv;
45
grdSearch.DataBind();
46
47
}
48
public
string
Highlight(
string
InputTxt)
49
{
50
string
Search_Str = txtSearch.Text.ToString();
51
// Setup the regular expression and add the Or operator.
52
Regex RegExp =
new
Regex(Search_Str.Replace(
" "
,
"|"
).Trim(),
53
RegexOptions.IgnoreCase);
54
55
// Highlight keywords by calling the
56
//delegate each time a keyword is found.
57
return
RegExp.Replace(InputTxt,
58
new
MatchEvaluator(ReplaceKeyWords));
59
60
// Set the RegExp to null.
61
RegExp =
null
;
62
63
}
64
65
public
string
ReplaceKeyWords(Match m)
66
{
67
68
return
"<span class="
highlight
">"
+ m.Value +
"</span>"
;
69
70
}
71
72
protected
void
txtSearch_TextChanged(
object
sender, EventArgs e)
73
{
74
SearchText();
75
}
VB.NET
01
Protected
Sub
Page_Load(sender
As
Object
, e
As
EventArgs)
02
If
Not
IsPostBack
Then
03
BindGrid()
04
End
If
05
End
Sub
06
Private
Function
GetRecords()
As
DataTable
07
Dim
conn
As
New
SqlConnection(strConnection)
08
conn.Open()
09
Dim
cmd
As
New
SqlCommand()
10
cmd.Connection = conn
11
cmd.CommandType = CommandType.Text
12
cmd.CommandText =
"Select * from Employees"
13
Dim
dAdapter
As
New
SqlDataAdapter()
14
dAdapter.SelectCommand = cmd
15
Dim
objDs
As
New
DataSet()
16
dAdapter.Fill(objDs)
17
Return
objDs.Tables(0)
18
19
End
Function
20
Private
Sub
BindGrid()
21
Dim
dt
As
DataTable = GetRecords()
22
If
dt.Rows.Count > 0
Then
23
grdSearch.DataSource = dt
24
grdSearch.DataBind()
25
End
If
26
End
Sub
27
Private
Sub
SearchText()
28
Dim
dt
As
DataTable = GetRecords()
29
Dim
dv
As
New
DataView(dt)
30
Dim
SearchExpression
As
String
=
Nothing
31
If
Not
[
String
].IsNullOrEmpty(txtSearch.Text)
Then
32
33
SearchExpression =
String
.Format(
"{0} '%{1}%'"
, grdSearch.SortExpression, txtSearch.Text)
34
End
If
35
dv.RowFilter =
"FirstName like"
& SearchExpression
36
grdSearch.DataSource = dv
37
grdSearch.DataBind()
38
39
End
Sub
40
Public
Function
Highlight(InputTxt
As
String
)
As
String
41
Dim
Search_Str
As
String
= txtSearch.Text.ToString()
42
' Setup the regular expression and add the Or operator.
43
Dim
RegExp
As
New
Regex(Search_Str.Replace(
" "
,
"|"
).Trim(), RegexOptions.IgnoreCase)
44
45
' Highlight keywords by calling the
46
'delegate each time a keyword is found.
47
Return
RegExp.Replace(InputTxt,
New
MatchEvaluator(
AddressOf
ReplaceKeyWords))
48
49
' Set the RegExp to null.
50
RegExp =
Nothing
51
52
End
Function
53
54
Public
Function
ReplaceKeyWords(m
As
Match)
As
String
55
56
Return
"<span class="
highlight
">"
& Convert.ToString(m.Value) &
"</span>"
57
58
End
Function
59
60
Protected
Sub
txtSearch_TextChanged(sender
As
Object
, e
As
EventArgs)
61
SearchText()
62
End
Sub
If you like this post than join us or share
16 comments:
Nice article
Thanks your article!
thanks for the article.it saved me a lot of research for doing such things
Very Nice Article. Lot useful in many Scenarios
Great Article !!
This is very nice example mention my you, this is helpful for programming logic.
Thanks
Shakti
www.nextmvp.blogspot.com
Very nice example thanx
how to do if the gridview is multi-page?
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..!
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
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
Good Article.
But I am having an error accessing the m value. I am doing in VB and thus it says - m not accessible bcoz of protection level. I tried to use
return RegExp.Replace(InputTxt,
new MatchEvaluator(addressof((ReplaceKeyWords(m))))
Which is throwing error at m.
Would be great if posted in vb.
Hey,great article..helped me a lot.
thanks dude.
It's very easy to understand and very useful thanks for ur submit this article.
this type of searching m finding few days.
Thanks
Twinkle Kumar
Great article, there is a slightly different example which I think is a bit simpler at http://blog.evonet.com.au/post/2008/06/25/Gridview-with-highlighted-search-results.aspx
im getting error Error 11 '_Default.GetRecords()': not all code paths return a value
Post a Comment