Searching in GridView With Paging Enabled
Some time back I blogged about searching in the GridView control (http://aspadvice.com/blogs/azamsharp/archive/2006/10/02/Searching-in-the-GridView-Control.aspx). Many users asked me that how will the example work if the paging is enabled. Although, it may seems like a difficult task but it is all too simple. Check out the complete code listed below. The main idea is to assign the searchString (protected string variable) the value from the textbox before going to the other page. This will save the searchString across multiple pages of the GridView control.
HTML Code:
<div>
Enter Search String: <asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" />
<asp:GridView ID="GridView1" AllowPaging="true" PageSize="10" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Product Name">
<ItemTemplate>
<%# HighlightText(searchString, (string) Eval("ProductName")) %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
C# Code Behind:
using
System;
using
System.Data;
using
System.Configuration;
using
System.Collections;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Web.UI.HtmlControls;
using
System.Data.SqlClient;
using
System.Text.RegularExpressions;
public
partial class GridViewSearching : System.Web.UI.
Page {
protected string searchString = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT ProductID, ProductName FROM Products", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected string HighlightText(string searchWord, string inputText)
{
Regex expression = new Regex(searchWord.Replace(" ", "|"), RegexOptions.IgnoreCase);
return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
}
public string ReplaceKeywords(Match m)
{
return "<span class='highlight'>" + m.Value + "</span>";
}
protected void Button1_Click(object sender, EventArgs e)
{
searchString = txtSearch.Text;
BindData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
searchString = txtSearch.Text; // move the text in the searchString variable :)
BindData();
}
}
Now, the above will work for GridView with multiple pages.