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

ASP.NET Gridview with Filter in Header

Rate me:
Please Sign up or sign in to vote.
4.83/5 (18 votes)
23 Jan 2014CPOL2 min read 178.3K   9.5K   30   15
This tip discribes how to implement filtering from inside ASP.NET gridview header row

Introduction

ASP.NET gridview by default provides facility for sorting and paging but no inbuilt facility to filter column. This article looks at possible way to implement filtering function within the gridview.

Background

I came across this requirement of having a gridview which allows filtering data from within the gridview. I also wanted to preserve the sorting and paging of the gridview.
Rather than creating separate panel above gridview for each of the fields to filter data, wouldn't it be nice to put a textbox along with each header column to filter data.
This leads me to this solution I derived for it. This may not be the best solution to do it but it definitely works. Our goal is to achieve this.

Image 1

Using the Code

  1. Create ASP.NET Web Application project in Visual Studio. First of all, we will create a DTO class to hold some data that we can display in a gridview. For this demo, I have created a DTO class of outstanding orders that contains some properties and some dummy data.

    C#
    [Serializable]
    public class Outstanding
    {
        public string Item { get; set; }
        public string Order { get; set; }
        public int Line { get; set; }
        public int Status { get; set; }
        public string ToLocation { get; set; }
        public decimal Qty { get; set; }
        public DateTime RegDate { get; set; }
        public string Location { get; set; }
        public decimal AllocQty { get; set; }
    
        public List<Outstanding> GetOutstanding()
        {
            List<Outstanding> lstOrders = new List<Outstanding>();
    
            lstOrders.Add(new Outstanding() { Item = "CocaCola",
            Order = "000101", Line = 1, Status = 20,
            ToLocation = "Sydney",
            Qty = 2000, RegDate = new DateTime(2014, 1, 1),
            Location = "USA", AllocQty = 100 });
            lstOrders.Add(new Outstanding() { Item = "BubbleGum",
            Order = "000101", Line = 1, Status = 20,
            ToLocation = "Sydney",
            Qty = 2500, RegDate = new DateTime(2014, 1, 11),
            Location = "USA", AllocQty = 300 });
            lstOrders.Add(new Outstanding() { Item = "Coffee",
            Order = "000111", Line = 1, Status = 50,
            ToLocation = "Melbourne",
            Qty = 2500, RegDate = new DateTime(2014, 1, 10),
            Location = "USA", AllocQty = 100 });
            lstOrders.Add(new Outstanding() { Item = "Sugar",
            Order = "000112", Line = 1, Status = 50,
            ToLocation = "Melbourne",
            Qty = 2300, RegDate = new DateTime(2014, 1, 10),
            Location = "NZ", AllocQty = 300 });
            lstOrders.Add(new Outstanding() { Item = "Milk",
            Order = "000112", Line = 1, Status = 50,
            ToLocation = "Melbourne",
            Qty = 2300, RegDate = new DateTime(2014, 1, 10),
            Location = "NZ", AllocQty = 200 });
            lstOrders.Add(new Outstanding() { Item = "Green Tea",
            Order = "000112", Line = 1, Status = 20,
            ToLocation = "Melbourne",
            Qty = 300, RegDate = new DateTime(2014, 1, 10),
            Location = "NZ", AllocQty = 220 });
            lstOrders.Add(new Outstanding() { Item = "Biscuit",
            Order = "000131", Line = 1, Status = 70,
            ToLocation = "Perth",
            Qty = 200, RegDate = new DateTime(2014, 1, 12),
            Location = "IND", AllocQty = 10 });
            lstOrders.Add(new Outstanding() { Item = "Wrap",
            Order = "000131", Line = 1, Status = 20,
            ToLocation = "Perth",
            Qty = 2100, RegDate = new DateTime(2014, 1, 12),
            Location = "IND", AllocQty = 110 });
    
            return lstOrders;
        }
    }
    
  2. Now in the Default.aspx page, add a gridview. To preserve sorting, add link button in HeaderTemplate with CommandName as "Sort" and CommandArgument as name of the column. Also, for the purpose of filtering the application will bind all the textboxes to single event (OnTextChanged="txtItem_TextChanged" ) and within the event we will determine which textbox fired it and take action accordingly. So columns of the gridview will look like this. I have used different filters like =,>,<,>=&<= for numeric data and "contains" filter for string values.

    ASP.NET
        <asp:TemplateField SortExpression="Item">
        <HeaderTemplate>
          <asp:LinkButton ID="lbItem" runat="server" Text="Item" 
          CommandName="Sort" CommandArgument="Item"></asp:LinkButton>
          <br />
          <asp:TextBox runat="server" ID="txtItem" AutoPostBack="true" 
          OnTextChanged="txtItem_TextChanged"></asp:TextBox>
        </HeaderTemplate>
        <ItemTemplate>
           <%#Eval("Item") %>
        </ItemTemplate>
        </asp:TemplateField><asp:TemplateField SortExpression="Line" 
        ItemStyle-HorizontalAlign="Right" HeaderStyle-HorizontalAlign="Right">
         <HeaderTemplate>
            <asp:LinkButton ID="lbLine" runat="server" Text="Line" 
            CommandName="Sort" CommandArgument="Line"
            CssClass="RightAlign"></asp:LinkButton>
          <br />
         <table>
          <tr>
           <td>
            <asp:DropDownList runat="server" 
            ID="ddlFilterTypeLine" CssClass="upperCaseText">
            <asp:ListItem Text="=" Value="=" 
            Selected="True"></asp:ListItem>
            <asp:ListItem Text=">" Value=">"></asp:ListItem>
             <asp:ListItem Text=">=" Value=">="></asp:ListItem>
             <asp:ListItem Text="<" Value="<"></asp:ListItem>
            <asp:ListItem Text="<="  Value="<="></asp:ListItem>
             </asp:DropDownList>
          </td>
         <td>
         <asp:TextBox runat="server" ID="txtLine" Width="50" 
         AutoPostBack="true" OnTextChanged="txtItem_TextChanged" 
         CssClass="upperCaseText"></asp:TextBox>
        </td>
    </tr>
    </table></HeaderTemplate>
    <ItemTemplate>
    <%#Eval("Line","{0:0}")%>
    </ItemTemplate>
    </asp:TemplateField> 
  3. Now in the Page_Load event, we will bind gridview to the dummy data. I have kept data in ViewState for this demo.

    C#
    if (!Page.IsPostBack)
               {
                   Outstanding objOutstanding = new Outstanding();
    
                   List<Outstanding> lstOutstandingOrders = new List<Outstanding>();
                   lstOutstandingOrders = objOutstanding.GetOutstanding();
    
                   ViewState["columnNameO"] = "RegDate";
                   grdViewOutstanding.DataSource = lstOutstandingOrders;
                   grdViewOutstanding.DataBind();
    
                   ViewState["lstOutstandingOrders"] = lstOutstandingOrders;
                   upnlOutstanding.Update();
               }
    
  4.  In the textbox's text change event, we will find out which textbox fired it by looking at the ID of a sender and take action accordingly. Finally, we will bind the data to gridview. To preserve the values in filter after postback, I created a seperate method which gets called everytime postback occurs and set values in corresponding textboxes and filters after postback.

    C#
    protected void txtItem_TextChanged(object sender, EventArgs e)
           {
    
               if (sender is TextBox)
               {
                   if (ViewState["lstOutstandingOrders"] != null)
                   {
                       List<Outstanding> allOutstanding =
                       (List<Outstanding>)ViewState["lstOutstandingOrders"];
                       TextBox txtBox = (TextBox)sender;
                       if (txtBox.ID == "txtItem") //Find out which textbox
                                       // fired the event  and take action
                       {
                           allOutstanding = allOutstanding.Where
                           (x => x.Item.Contains(txtBox.Text.Trim().ToUpper())).ToList();
                           ViewState["OItemNo"] = txtBox.Text.Trim().ToUpper();
    
                       }
                       else if (txtBox.ID == "txtOrder")
                       {
                           allOutstanding = allOutstanding.Where(x =>
                           x.Order.Contains(txtBox.Text.Trim().ToUpper())).ToList();
                           ViewState["OOrder"] = txtBox.Text.Trim().ToUpper();
    
                       }
                       else if (txtBox.ID == "txtLine")
                       {
                           string filtrerType = ((DropDownList)grdViewOutstanding.HeaderRow.FindControl
                           ("ddlFilterTypeLine")).SelectedItem.Value;
    
                           if (filtrerType == "=")
                           {
                               allOutstanding = allOutstanding.Where
                                   (x => x.Line == int.Parse(txtBox.Text.Trim())).ToList();
                           }
                           else if (filtrerType == ">")
                           {
                               allOutstanding = allOutstanding.Where
                               (x => x.Line > int.Parse(txtBox.Text.Trim())).ToList();
                           }
                           else if (filtrerType == ">=")
                           {
                               allOutstanding = allOutstanding.Where
                               (x => x.Line >= int.Parse(txtBox.Text.Trim())).ToList();
                           }
                           else if (filtrerType == "<")
                           {
                               allOutstanding = allOutstanding.Where
                               (x => x.Line < int.Parse(txtBox.Text.Trim())).ToList();
                           }
                           else if (filtrerType == "<=")
                           {
                               allOutstanding = allOutstanding.Where
                               (x => x.Line <= int.Parse(txtBox.Text.Trim())).ToList();
                           }
                           ViewState["OFilterLine"] = filtrerType;
                           ViewState["OLine"] = txtBox.Text.Trim();
    
                       } ..... ....ViewState["lstOutstandingOrders"] = allOutstanding;
                       grdViewOutstanding.DataSource = allOutstanding;
                       grdViewOutstanding.DataBind();ResetFilterAndValueOutstanding();
    
  5.  ResetFilterAndValueOutstanding() method restores values in filter textbox and filter type in dropdown after each postback.

    C#
    protected void ResetFilterAndValueOutstanding()
           {
               if (ViewState["OItemNo"] != null)
                   ((TextBox)grdViewOutstanding.HeaderRow.FindControl("txtItem")).Text =
                   ViewState["OItemNo"].ToString().ToUpper();
               if (ViewState["OOrder"] != null)
                   ((TextBox)grdViewOutstanding.HeaderRow.FindControl("txtOrder")).Text =
                   ViewState["OOrder"].ToString().ToUpper();
               if (ViewState["OFilterLine"] != null)
               {
                   foreach (ListItem li in
                   ((DropDownList)grdViewOutstanding.HeaderRow.FindControl("ddlFilterTypeLine")).Items)
                   {
                       if (li.Text == ViewState["OFilterLine"].ToString())
                       li.Selected = true; else li.Selected = false;
                   }
               }....
    
  6. Add a link button on top of the gridview called "Remove Filter" which will reset all the ViewStates and rebind gridview to data and reset all filters to its original values.

    C#
    protected void lbRemoveFilterOutstanding_Click(object sender, EventArgs e)
           {
               if (ViewState["OItemNo"] != null) ViewState["OItemNo"] = null;
               if (ViewState["OOrder"] != null) ViewState["OOrder"] = null;
               if (ViewState["OFilterLine"] != null) ViewState["OFilterLine"] = null;
               if (ViewState["OLine"] != null) ViewState["OLine"] = null;
               if (ViewState["OFilterStatus"] != null) ViewState["OFilterStatus"] = null;
               if (ViewState["OStatus"] != null) ViewState["OStatus"] = null;
               if (ViewState["OLocation"] != null) ViewState["OLocation"] = null;
               if (ViewState["OToLocation"] != null) ViewState["OToLocation"] = null;
               if (ViewState["OFilterQty"] != null) ViewState["OFilterQty"] = null;
               if (ViewState["OQty"] != null) ViewState["OQty"] = null;
               if (ViewState["OFilterAllocQty"] != null) ViewState["OFilterAllocQty"] = null;
               if (ViewState["OAllocQty"] != null) ViewState["OAllocQty"] = null;
               if (ViewState["OFilterRegDate"] != null) ViewState["OFilterRegDate"] = null;
               if (ViewState["ORegDate"] != null) ViewState["ORegDate"] = null;
    
               Outstanding objOutstanding = new Outstanding();
               List<Outstanding> lstOutstandingOrders = new List<Outstanding>();
               lstOutstandingOrders = objOutstanding.GetOutstanding();
    
               grdViewOutstanding.DataSource = lstOutstandingOrders;
               grdViewOutstanding.DataBind();
    
               ViewState["lstOutstandingOrders"] = lstOutstandingOrders;
           }
    

Points of Interest

Gridview does not support filtering of data directly but it can be implemented using TemplateField in the Gridview.

History

  • 22rd January, 2014: Initial post

License

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


Written By
Software Developer (Senior)
Australia Australia
I am currently working as a Software Developer in .NET technologies.

Languages & Technologies I have worked on so far:

Pascal ... My first programming language..baby steps..
8085 Assembler ... Amazing how it all works internally in computer brain... "intel inside"
C... missing my point(er)....
C++... Its all about classes ...
LISP ... Did I missed any parenthesis ?
VB... Oh dear... Just like a war stories.. those are the days
Java... I learn to program this in notepad...
C#... Oh what a smooth sailing...
ASP.NET... web is the future ...
Oracle ... Not the one from "The Matrix"...
MSSQL... select Programming from Universe where StartTime >='BigBang'
Wireless Sensor Networks ... Look who is talking too ?

Comments and Discussions

 
AnswerThank you Pin
aravinth santosh15-Dec-14 9:27
aravinth santosh15-Dec-14 9:27 
QuestionProblem with filtering Pin
Member 1122788124-Nov-14 3:58
Member 1122788124-Nov-14 3:58 
AnswerRe: Problem with filtering Pin
virang_2124-Nov-14 10:56
virang_2124-Nov-14 10:56 
Replace Item.Contains() with Item.ToUpper().Contains()

allOutstanding = allOutstanding.Where(x => x.Item.ToUpper().Contains(txtBox.Text.Trim().ToUpper())).ToList();

This is required when running against LINQ to Objects as Contains become case sensitive.

Zen and the art of software maintenance : rm -rf *

Maths is like love : a simple idea but it can get complicated.

QuestionProblem with filtering Pin
esb7719-Nov-14 12:00
esb7719-Nov-14 12:00 
AnswerRe: Problem with filtering Pin
virang_2119-Nov-14 14:00
virang_2119-Nov-14 14:00 
GeneralRe: Problem with filtering Pin
esb7719-Nov-14 14:29
esb7719-Nov-14 14:29 
GeneralRe: Problem with filtering Pin
esb7719-Nov-14 14:43
esb7719-Nov-14 14:43 
GeneralRe: Problem with filtering Pin
esb7719-Nov-14 14:59
esb7719-Nov-14 14:59 
QuestionASP.NET Gridview with Filter in Header Pin
Usman Mohammed16-Oct-14 21:48
Usman Mohammed16-Oct-14 21:48 
AnswerRe: ASP.NET Gridview with Filter in Header Pin
virang_2119-Oct-14 14:25
virang_2119-Oct-14 14:25 
QuestionOnly one filter? Pin
Claire Streb19-Aug-14 10:44
Claire Streb19-Aug-14 10:44 
AnswerRe: Only one filter? Pin
virang_2119-Aug-14 11:20
virang_2119-Aug-14 11:20 
GeneralRe: Only one filter? Pin
Claire Streb25-Aug-14 14:24
Claire Streb25-Aug-14 14:24 
AnswerToLocation Pin
Member 104111079-Apr-14 3:21
Member 104111079-Apr-14 3:21 
Questionit seems fine Pin
blachsmith24-Jan-14 14:06
blachsmith24-Jan-14 14:06 

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.