In this article I will explain with an example, 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
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The following
HTML Markup consists of:
GridView - For displaying data.
Columns
The
GridView consists of three
BoundField columns.
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" HtmlEncode="false" />
<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
Inside the Page_Load and Search event handler, the BindGrid method is called.
Inside the BindGrid method, LIKE search SQL query is 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
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.DataRowThen
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
Demo
Downloads