Wednesday, January 20, 2010

Searching in the GridView control with paging enabled using Asp.Net C# 2.0 / 3.5




Please visit my new Web Site WWW.Codedisplay.com



In many forums Asp.net C# Vb.Net developers ask a common question How one can search in a GridView and highlight GridView rows or record data. The answer is yes we found a lot of example on this issue and here in this example i am going to explain how you can highlight gridview rows data based on search result. As we know that GridView control is a very nice and helpful control but still can't provide us such facility to search within gridview and highlight data. To do that first add a page in your project then add a textbox and a commandbutton to search within the gridview. After that add a GridView control & bind with data. In this example i will skip how to bind data in GridvIew since its out of scope of this article. Here in this example i will show only how one can search within the GridView control easily. Also i would like to show you how you can search within gridview even the GridView has paging functionality. I would also like to show you how you can search within all Gridview rows & all columns.






Now under code file write the below two methods:
protected string HighlightText(string searchWord, string inputText)
    {
        // Replace spaces by | for Regular Expressions
        Regex expression = new Regex(search_Word.Replace(" ", "|"), RegexOptions.IgnoreCase);
        return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
    }

    public string ReplaceKeywords(Match m)
    {
        return "<span class='highlight'>" + m.Value + "</span>";
    }
Now under search button write the below code:
protected void cmdSearch_Click(object sender, EventArgs e)
    {
        // Assign search_Word
        search_Word = txtSearch.Text;
        RefreshData();
    }
Ohh one anotherthing is i will explain also how you can highlight gridview data based on search result even the GridView has paging functionality. To do that write the below code under PageIndexChanging event:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        search_Word = txtSearch.Text;
        RefreshData();
    }
Now look at the below GridView HTML Markup:
<asp:GridView ID="GridView1" runat="server" Width="400px" AutoGenerateColumns="False" 
        AllowPaging="true" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
            <asp:TemplateField HeaderText="Brand Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Brand Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
            <asp:TemplateField HeaderText="Category Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Category Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
            <asp:TemplateField HeaderText="Product Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Product Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
        </Columns>
        </asp:GridView>
If you have more column just apply the above technique for each column to search.

Now add the below CSS in your page:
<style type="text/css">
    .highlight
    {
        background-Color:Yellow;
    }
    </style>
The output will be:

The complete HTML markup code is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Search.aspx.cs" Inherits="GridView_Search" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>How to search within GridView</title>
    <style type="text/css">
    .highlight
    {
        background-Color:Yellow;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <asp:Button ID="cmdSearch" runat="server" Text="Search" OnClick="cmdSearch_Click" />
    <br />
        <asp:GridView ID="GridView1" runat="server" Width="400px" AutoGenerateColumns="False" 
        AllowPaging="true" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
            <asp:TemplateField HeaderText="Brand Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Brand Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
            <asp:TemplateField HeaderText="Category Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Category Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
            <asp:TemplateField HeaderText="Product Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Product Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
        </Columns>
        </asp:GridView>    
    
    </div>
    </form>
</body>
</html>
The complete server side code is:
using System;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class GridView_Search : System.Web.UI.Page
{
    protected string search_Word = String.Empty;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            RefreshData();
    }

    protected string HighlightText(string searchWord, string inputText)
    {
        // Replace spaces by | for Regular Expressions
        Regex expression = new Regex(search_Word.Replace(" ", "|"), RegexOptions.IgnoreCase);
        return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
    }

    public string ReplaceKeywords(Match m)
    {
        return "" + m.Value + "";
    }
    
    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        // Assign search_Word
        search_Word = txtSearch.Text;
        RefreshData();
    }
    
    protected void RefreshData()
    {
        // Here bind the gridview
        GridView1.DataSource = clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], " +
        "P.Name [Product Name] FROM " +
        "Brand B, Category C, Product P " +
        "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
        GridView1.DataBind();
    }
    
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        search_Word = txtSearch.Text;
        RefreshData();
    }
}
Hope now you can search within GridView control as well as can highlight search word based on search result.

Ref: http://aspnet.4guysfromrolla.com/articles/072402-1.aspx

1 comments:

Smith said...

Good Article.
Can you provide with a snippet where Autogenerate columns is True and I am not sure what the Column Names would be.

You can e-mail to smithspd@live.com
Thanks

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash