Saturday, November 28, 2015

Asp.net: Search and highlight the text In Gridview

In this article I am going to explain how to search the record and highlight in Gridview using Asp.net

In the previous article I have explained Open image in popup using jquery and Imagehover effect using CSS

Description:
I have created a table Tb_movie and displaying the records in gridview data control.

I want to filter the records based on movie name. To implement this functionality I have create two procedure one to bind the data to gridview and another one to filter the record.

Implementation:

Store procedure to get the data:
Create proc [dbo].[SpGetMovie]
AS
BEGIN
Select * from dbo.Tb_Movie
End
Store procedure to filter (search) the record:
Create PROCEDURE [dbo].[SpFilterMovie]
(
@name varchar(100)
)
AS
BEGIN
            SET NOCOUNT ON;
Select * from dbo.Tb_Movie where Name like @name +'%'
END

Now add a webform to project. Add the textbox, 2 buttons (one to search and another one to clear the searched text) and gridview to webform.
HTML Markup:
<table>
    <tr><td><asp:TextBox ID="txtsearch" runat="server"></asp:TextBox></td><td><asp:Button ID="Button1" runat="server" Text="Search" /></td><td>
        <asp:Button ID="btnclear" runat="server" Text="Clear" /></td></tr>
     <tr><td></td><td></td><td></td></tr>
      <tr><td colspan="3"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
        <asp:BoundField DataField="name" HeaderText="Name" />
        <asp:BoundField DataField="genre" HeaderText="Genre" />
        <asp:BoundField DataField="Budget" HeaderText="Budget" />
        </Columns>
        </asp:GridView></td></tr>
       <tr><td></td><td></td><td></td></tr>       
    </table>

Import the namespace
C# code:
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Text.RegularExpressions;

VB code:
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data
Imports System.Text.RegularExpressions

Create sqlconnection
C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());

VB Code:
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

Bind the Gridview
Create a function to bind the gridview and call it on page load event.

C# code:
  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    private void BindGrid()
    {
        SqlDataAdapter adp = new SqlDataAdapter("SpGetMovie", con);
        adp.SelectCommand.CommandType = CommandType.StoredProcedure;
        DataTable dt = new DataTable();
        adp.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

VB code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindGrid()
        End If
    End Sub
    Private Sub BindGrid()
        Dim adp As New SqlDataAdapter("SpGetMovie", con)
        adp.SelectCommand.CommandType = CommandType.StoredProcedure
        Dim dt As New DataTable()
        adp.Fill(dt)
        If dt.Rows.Count > 0 Then
            GridView1.DataSource = dt
            GridView1.DataBind()
        End If
    End Sub

Search the record
On search button click write the below given code
C# code:
protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("SpFilterMovie",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@name", txtsearch.Text);
            DataTable dt = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);           
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
        }
    }  

VB code:
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        Try
            Dim cmd As New SqlCommand("SpFilterMovie", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@name", txtsearch.Text)
            Dim dt As New DataTable()
            Dim adp As New SqlDataAdapter(cmd)
            adp.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
        Catch ex As Exception
        End Try
    End Sub

Highlight the search text (keyword) in gridview
On rowdatabound event of gridview write the below given code to highlight the search text (keyword)
C# code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Text = Regex.Replace(e.Row.Cells[0].Text, txtsearch.Text.Trim(), delegate(Match match)
            {
                return string.Format("<span style = 'background-color:#FBEDBB'>{0}</span>", match.Value);
            }, RegexOptions.IgnoreCase);
        } 
    }

VB code:
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            e.Row.Cells(0).Text = Regex.Replace(e.Row.Cells(0).Text, txtsearch.Text.Trim(), Function(match As Match) String.Format("<span style = 'background-color:#FBEDBB'>{0}</span>", match.Value), RegexOptions.IgnoreCase)
        End If
    End Sub

Clear the searched text
On button clear call the bindgrid function and clear the search textbox.
C# code:
protected void btnclear_Click(object sender, EventArgs e)
    {
        txtsearch.Text = String.Empty;
        BindGrid();
    }

VB code:
Protected Sub btnclear_Click(sender As Object, e As System.EventArgs) Handles btnclear.Click
        txtsearch.Text = String.Empty
        BindGrid()
    End Sub

Build, run the project and test it.

Demo:
Asp.net: Search and highlight the text In Gridview
   In this article we have learn how to highlight the search text(keyword) in asp.net (C#, VB.net) . I hope you enjoyed this article. 

No comments:

Post a Comment