In this article I will explain how to search records in GridView and highlight the results in ASP.Net using C# and VB.Net.
Inside the RowDataBound event handler, the search text (keywords) will be highlighted using Regular Expression Replace function.
 
 
Database
For this article I have used Microsoft’s Northwind database. You can download it using the link provided below.
 
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView with BoundField columns. I have specified OnRowDataBound and OnPageIndexChanging events which will be used highlight the search text (keywords) and perform pagination in GridView respectively.
Search:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button Text="Search" runat="server" OnClick="Search" />
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" AllowPaging="true" OnRowDataBound="OnRowDataBound" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
    <asp:BoundField HeaderStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name"
        ItemStyle-CssClass="ContactName" />
    <asp:BoundField HeaderStyle-Width="150px" DataField="City" HeaderText="City" />
    <asp:BoundField HeaderStyle-Width="150px" DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
 
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Text.RegularExpressions
 
 
Populating and Searching in GridView
The BindGrid function is used to populate and implement search the GridView. It uses a LIKE search SQL query to fetch records from the Customers table of the Northwind database. This method is called on Page_Load event handler as well as on the Click event handler of the Search button.
There’s also a OnPageIndexChanging event which is used to perform pagination in the ASP.Net GridView control.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
protected void Search(object sender, EventArgs e)
{
    this.BindGrid();
}
 
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT ContactName, City, Country FROM Customers WHERE ContactName LIKE '%' + @ContactName + '%'";
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@ContactName", txtSearch.Text.Trim());
            DataTable dt = new DataTable();
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                sda.Fill(dt);
                gvCustomers.DataSource = dt;
                gvCustomers.DataBind();
            }
        }
    }
}
 
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvCustomers.PageIndex = e.NewPageIndex;
    this.BindGrid();
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Protected Sub Search(sender As Object, e As EventArgs)
    Me.BindGrid()
End Sub
 
Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand()
            cmd.CommandText = "SELECT ContactName, City, Country FROM Customers WHERE ContactName LIKE '%' + @ContactName + '%'"
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@ContactName", txtSearch.Text.Trim())
            Dim dt As New DataTable()
            Using sda As New SqlDataAdapter(cmd)
                sda.Fill(dt)
                gvCustomers.DataSource = dt
                gvCustomers.DataBind()
            End Using
        End Using
    End Using
End Sub
 
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
    gvCustomers.PageIndex = e.NewPageIndex
    Me.BindGrid()
End Sub
 
Search records in GridView and highlight results in ASP.Net using C# and VB.Net
 
 
Highlight Search Text (Keywords) in Search Results of the GridView
Inside the OnRowDataBound event handler, the search text (keywords) is highlighted in the Search results.
In each GridView row the cell’s text is replaced with the highlighted search results using the Regular Expression’s Replace function.
C#
protected void OnRowDataBound(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:#D9EDF7'>{0}</span>", match.Value);
        }, RegexOptions.IgnoreCase);
    }
}
 
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
    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:#D9EDF7'>{0}</span>", match.Value), _
                        RegexOptions.IgnoreCase)
    End If
End Sub
 
Search records in GridView and highlight results in ASP.Net using C# and VB.Net
 
 
Demo
 
 
Downloads