In this article I will explain how to search records in gridview and highlight search keywords in gridview using asp.net.
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.
ColumnName | DataType |
UserId | Int(set identity property=true) |
UserName | varchar(50) |
LastName | varchar(50) |
Location | varchar(50) |
<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" /> <asp:ImageButton ID="btnSearch" ImageUrl="~/SearchButton.png" runat="server" Style="top: 5px; position: relative" onclick="btnSearch_Click" /> <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> |
using System; using System.Text.RegularExpressions; using System.Web.UI; |
// 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(); } |
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 |
<connectionStrings> <add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/> </connectionStrings> |
![]() |
|
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 Email
|
|||
|
|
|


Subscribe by RSS
Subscribe by Email
41 comments :
Great work sir, I am searching for this code from long time..thnx
Very Easy and useful way for my Difficulty
Thanks sir for ur valuable guidenace
thank u sir greate work.........,
What if your column you're searching for has spaces? How would you return that value?
Very Very Nice Site. Excellent Work Done.
Thanks Team of Aspdotner-suresh.com web
hello sir,
wil u plz make the same project with the help of datareader. i need it in my project
Very nice!!! Great work
superb site.....it very useful site for all ...
Thanks to suresh.
Awesome!! Thanks so much for the useful info. :)
Am i missing something here? Because when i click my search button im not getting anything?
I did not get anything either.
Eugene
nice post suresh.
how to hight light bound field meand 'Datafield" in gridview
how to hight light bound field meand 'Datafield" in gridview
hi sir ....
It is not working
it just display all data from database
and not highlight any row when i am search....
@Chetan patil...
Check your code I hope you did mistake in highlight text method.
hi sir.....
how to use this article in asp.net with mvc .
please help me
owsome thanks bro
This is great suresh. Any idea how can i highlight the whole row instead? Thanks in advance.
Hi, thanks for sharing this..by the way, how about multiple search text fields?I'm having prob with it.
Thanks
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
Simple and useful, thanks!
i want it windows application vb.net can u guys help me out
i want it windows application vb.net can u guys help me out
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.
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
Hi Suresh,
Can you help me in scrolling images
using jquery with asp.net and c#
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
OnClicking back button, the highlighted text is not losing its style, the highlighted text still gets displayed.
hot to write it using C#???
if i use two or three textbox to find result then what should i do
SUBASH
Sir, I want to filter rows in grid view using mobile number on text Changed events plz help me
Great Work ........Found this
How it will work to search in last name and Location also
Thanks sir
for guidenace
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...
It is as great and simple like you, You are such a champion coder.
very nice
Can i have this code in vb.net