If you have implemented a GridView in your ASP.NET web project, there can be needed to implement search GridView records using Textbox, so here in this article I am going to explain quickly, how you can achieve this by calling a C# function on input textbox OnTextChanged and return matched GridView rows with Highlighting searched terms.
Step 1: Create a Web Forms project in your Visual Studio, by navigating to File -> New -> Project (Select 'Web' from left pane & Select 'ASP.NET web application' from right pane)
Select "Web-Forms" template and Click "OK".
Step 2: Create database table & columns to be used on the GridView, here we will be using the below table
You can create the table(with data) using the script
USE [Students]
GO
/****** Object: Table [dbo].[Student_details] Script Date: 4/16/2018 5:11:16 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Student_details](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[Class] [varchar](50) NULL,
CONSTRAINT [PK_Student_details] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Student_details] ON
INSERT [dbo].[Student_details] ([Id], [Name], [Email], [Class]) VALUES (1, N'Suresh Wahi', N'suresh_wahi@gmail.com', N'Class X')
INSERT [dbo].[Student_details] ([Id], [Name], [Email], [Class]) VALUES (2, N'Ramesh taurani', N'ramesh.taurani@gmail.com', N'Class X')
INSERT [dbo].[Student_details] ([Id], [Name], [Email], [Class]) VALUES (3, N'Preetam', N'preeetam@gmail.com', N'Class XI')
INSERT [dbo].[Student_details] ([Id], [Name], [Email], [Class]) VALUES (4, N'Surendra', N'Surendra@gmail.com', N'Class X')
INSERT [dbo].[Student_details] ([Id], [Name], [Email], [Class]) VALUES (5, N'Martin ', N'Martin@gmail.com', N'Class XI')
INSERT [dbo].[Student_details] ([Id], [Name], [Email], [Class]) VALUES (6, N'Maria', N'maria@gmail.com', N'Class X')
INSERT [dbo].[Student_details] ([Id], [Name], [Email], [Class]) VALUES (7, N'Preeti', N'preeti@gmail.com', N'Class X')
SET IDENTITY_INSERT [dbo].[Student_details] OFF
Step 3: Go to Default.aspx (Create on if it doesn't exist), and use the code below to show the above table data in GridView
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SearchFilterInGridView._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<br/>
Enter first name to search:
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True"
OnTextChanged="txtSearch_TextChanged" />
<br/>
<br/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="grdSearch" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server"
Text='<%# Highlight(Eval("Name").ToString()) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="Email" runat="server" Text='<%#(Eval("Email")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Class">
<ItemTemplate>
<asp:Label ID="Email" runat="server" Text='<%#(Eval("Class")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
Note: In the above .aspx page, I am using master page also and just rendering main content of the body here, so if you don't have a master page already created, here is the code for the master page
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="SearchFilterInGridView.SiteMaster" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%: Page.Title %> - My ASP.NET Application</title>
<style>
.HighLightedWord
{
text-decoration:underline;
font-weight:bold;
}
</style>
<asp:PlaceHolder runat="server">
<%: Scripts.Render("~/bundles/modernizr") %>
</asp:PlaceHolder>
<webopt:bundlereference runat="server" path="~/Content/css" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
</head>
<body>
<form runat="server">
<asp:ScriptManager runat="server">
<Scripts>
<%--To learn more about bundling scripts in ScriptManager see https://go.microsoft.com/fwlink/?LinkID=301884 --%>
<%--Framework Scripts--%>
<asp:ScriptReference Name="MsAjaxBundle" />
<asp:ScriptReference Name="jquery" />
<asp:ScriptReference Name="bootstrap" />
<asp:ScriptReference Name="respond" />
<asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
<asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
<asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
<asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
<asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
<asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
<asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
<asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
<asp:ScriptReference Name="WebFormsBundle" />
<%--Site Scripts--%>
</Scripts>
</asp:ScriptManager>
<div class="container body-content">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
<hr />
<footer>
<p>© <%: DateTime.Now.Year %> - My ASP.NET Application</p>
</footer>
</div>
</form>
</body>
</html>
Step 4: In your Default.aspx.cs(Code Behind) file, first you will need to get the complete table data from the database on page load (GetRecords) and then create a function to be called on textbox value change(txtSearch_TextChanged which calls SearchText).
C# code for it
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private DataTable GetRecords()
{
SqlConnection conn = new SqlConnection(@"Data Source=DataDource;Initial Catalog=Students;User ID=userId;Password=password");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Student_details";
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
return objDs.Tables[0];
}
private void BindGrid()
{
DataTable dt = GetRecords();
if (dt.Rows.Count > 0)
{
grdSearch.DataSource = dt;
grdSearch.DataBind();
}
}
//Called on input textbox value is changed
private void SearchText()
{
DataTable dt = GetRecords();
DataView dv = new DataView(dt);
string SearchExpression = null;
//check if value is null or not, if not search it
if (!String.IsNullOrEmpty(txtSearch.Text))
{
SearchExpression = string.Format("{0} '%{1}%'",
grdSearch.SortExpression, txtSearch.Text);
dv.RowFilter = "Name like" + SearchExpression;
grdSearch.DataSource = dv;
grdSearch.DataBind();
}
grdSearch.DataSource = dv;
grdSearch.DataBind();
}
//this function returns the highlighted code html
public string Highlight(string InputTxt)
{
string Search_Str = txtSearch.Text.ToString();
// 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));
}
//wrap the hightlighted code inside html
public string ReplaceKeyWords(Match m)
{
return "<span class='HighLightedWord'>" + m.Value + "</span>";
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchText();
}
}
In the above C# code, we are calling txtSearch_TextChanged function when textbox value is changed to be searched, as soon as data is not null or empty it is searched and new GridView data is filled, now for highlighting part, here is the code which returns wrap the highlighted terms inside separate span with CSS class 'HighLightedWord'
//this function returns the highlighted code html
public string Highlight(string InputTxt)
{
string Search_Str = txtSearch.Text.ToString();
// 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));
}
//wrap the highlighted terms inside separate span with css class HighLightedWord
public string ReplaceKeyWords(Match m)
{
return "<span class='HighLightedWord'>" + m.Value + "</span>";
}
As you can see in the above code, we are using HighLightedWord CSS class, here are the class properties, which we have defined in the master page
<style>
.HighLightedWord
{
text-decoration:underline;
font-weight:bold;
}
</style>
Step 5: Build your project and run it in the browser, the output will be as below
We are done with our search filter, feel free to post your questions related to articles in the below comments section.
You can download the source code of project(Database script is not included, use the Step 2 scripts).