Click here to Skip to main content
15,881,248 members
Articles / Web Development / ASP.NET

Gridview Header Filter

Rate me:
Please Sign up or sign in to vote.
4.23/5 (12 votes)
22 Apr 2010CPOL1 min read 98.2K   5.2K   28   6
To help you filter gridview using its header

Introduction

Most of the time, we need to filter gridview based on some filtering criteria. This article will show you how to filter using the gridview header. This is small but really useful stuff. You can extend it to suite your needs.

Background

Following are the prerequisites for this project:

  1. VS 2008 with Service Pack 1
  2. Ajax control toolkit DLL

Using the Code

The code is extremely simple and easy to use.

Define a HeaderTemplate for the column you want to filter on. Simply add a textbox with borderstyle set to None, AutoPostBack set to true and BackColor set to transparent. This will give a feel of label. Create a TextBoxWaterMarkExtender with TargetControlID set to the id of previous textbox. Set the WaterMarktext to the Header text you want to display.

ASP.NET
<HeaderTemplate>
<asp:TextBox ID="txtCategoryNameHeader" runat="server" 

BorderStyle="None" AutoPostBack="true" BackColor="Transparent" 

OnTextChanged="txtCategoryNameHeader_TextChanged" ></asp:TextBox>
<asp:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server" 

TargetControlID="txtCategoryNameHeader" WatermarkText="Category">
</asp:TextBoxWatermarkExtender>
</HeaderTemplate>   

Once you set the HTML tag, you can code it. You need to bind the txtCategoryNameHeader_TextChanged event with the following line of code:

C#
((TextBox)this.gvCategory.HeaderRow.Cells[1].Controls[1]).TextChanged += 
						new System.EventHandler

(this.txtCategoryNameHeader_TextChanged);

Once you enter some text inside the header textbox, a post back event will fire and the following method will be executed:

C#
protected void txtCategoryNameHeader_TextChanged(object sender, EventArgs e)
        {
            string text = ((TextBox)sender).Text;
            BindCategories(text);
        }

Rest of the filtering criteria is pretty self explanatory, so I wouldn't further explain it. Hope this will help you guys.

C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Bind the categories with Grid
                BindCategories(string.Empty);
                // This is used to bind the textbox header with the event to fire when 
                ((TextBox)this.gvCategory.HeaderRow.Cells[1].Controls[1]).TextChanged 
					+= new System.EventHandler

(this.txtCategoryNameHeader_TextChanged);
            }
        }
        private void BindCategories(string CategoryFilter)
        {            
            try
            {
                // Simple created a table to bind with Grid view and 
                // populated it with data.
                DataTable dt = new DataTable("Category");
                dt.Columns.Add("ID");
                dt.Columns.Add("Name");
                DataRow dr ;
                for(int counter=1;counter<11;counter++)
                {
                    dr = dt.NewRow();
                    dr["ID"]=counter.ToString();
                    dr["Name"]= "Cat" + counter.ToString();
                    dt.Rows.Add(dr);
                }

                DataView dv = new DataView(dt);
                if(CategoryFilter != "")
                    dv.RowFilter="Name like '%" + CategoryFilter + "%'";

                if (CategoryFilter == "")
                    gvCategory.DataSource = dv;
                else
                    gvCategory.DataSource = dv;
                gvCategory.DataBind();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                
            }
        }
        
        protected void txtCategoryNameHeader_TextChanged(object sender, EventArgs e)
        {
            string text = ((TextBox)sender).Text;
            BindCategories(text);
        }

Points of Interest

There do exist several ways to manipulate gridview and I found this one interesting so I just published it. For daily technical stuff, checkout my blog at http://hellowahab.blogspot.com/.

History

  • 16th April, 2010: First version published

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Pakistan Pakistan
Follow my blogging activities here:-
http://www.hellowahab.wordpress.com

Follow my professional activities here:-
http://www.linkedin.com/in/hellowahab

Follow my tweets here:-
http://twitter.com/#!/hellowahab

Follow my personal activities here:-
https://www.facebook.com/hellowahab

Comments and Discussions

 
GeneralMy vote of 4 Pin
diogonborges7-Jan-13 5:08
diogonborges7-Jan-13 5:08 
QuestionGridView disappears Pin
Homey8323-Nov-11 11:16
Homey8323-Nov-11 11:16 
Questionvariation Pin
Sean80848-Sep-11 7:30
Sean80848-Sep-11 7:30 
GeneralMy 5 Pin
Omar Gameel Salem1-Jun-11 4:34
professionalOmar Gameel Salem1-Jun-11 4:34 
Good work Wink | ;)
just one thing
if (CategoryFilter == "")
  gvCategory.DataSource = dv;
else
  gvCategory.DataSource = dv;

GeneralMy vote of 5 Pin
Member 41788502-Jul-10 3:05
Member 41788502-Jul-10 3:05 
GeneralUsing < > = in Pin
JanBorup3-May-10 11:20
JanBorup3-May-10 11:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.