Tuesday, October 23, 2012

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


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-size100%font-family'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial,Helevetica, sans-serifcolor#303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em0.5em 0.5em 0.5em;text-align:center
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em0.5em;}
.Gridview tr{colorBlackbackground-colorWhitetext-align:left}
:link,:visited { color#DF4F13text-decoration:none }
.highlight {text-decorationnone;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="top5pxpositionrelative" onclick="btnSearch_Click" />&nbsp;&nbsp;
<asp:ImageButton ID="btnClear" ImageUrl="~/Clearbutton.png" runat="server" Style="top5px;
positionrelative" 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 ObjectByVal e As EventArgs)
End Sub

Public Function HighlightText(ByVal InputTxt As StringAs 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 ObjectByVal e As ImageClickEventArgs)
'  Set the value of the SearchString so it gets
SearchString = txtSearch.Text
End Sub

Protected Sub btnClear_Click(ByVal sender As ObjectByVal 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





source: http://www.aspdotnet-suresh.com/2011/12/search-records-in-gridview-and.html

No comments:

Post a Comment