Monday, December 29, 2014

How to highlight search results in Gridview using asp.net C#

Introduction:
In this article I will explain how to search records in 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




<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" 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>

</form>
</body>
</html>
Open code behind file and add following namespaces  

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)
{
    if (!IsPostBack)
        {
            BindGridview();
        }
}
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 ("" + m.Value + "");
}
protected void btnSearch_Click(object sender, ImageClickEventArgs e)
{
//  Set the value of the SearchString so it gets
SearchString = txtSearch.Text;
 BindGridview();
}
protected void btnClear_Click(object sender, ImageClickEventArgs e)
{
//  Simple clean up text to return the Gridview to it's default state
txtSearch.Text = "";
SearchString = "";
BindGridview();
}
//  Bind The GridVisa with DataTable 
protected void BindGridview()
    {
        DataTable dt = new DataTable();       

        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Education", typeof(string));
        dt.Columns.Add("Location", typeof(string));
        dt.Rows.Add(1, "Muhammed Asad", "BCIT" , "Karachi");
        dt.Rows.Add(2, "Muhammed Ali", "Msc", "Karachi");
        dt.Rows.Add(3, "Madhav Sai", "MS", "Karachi");
        dt.Rows.Add(4, "Asma", "MBA", "Karachi");
        dt.Rows.Add(6, "Faheem Shah", "MBBS", "Karachi");
        dt.Rows.Add(7, "Asif Raza", "B.Tech", "Karachi");
        dt.Rows.Add(8, "Daniel", "CA", "Karachi");
        gvDetails.DataSource = dt;
        gvDetails.DataBind();       
    }
Damo:


Download Sample Code:

No comments:

Post a Comment