AspdotnetCodes.com
ASP.NET 3.5 Web Hosting – Click Here
 
Articles Subscribe for our Articles Updates
Books
Resources
Downloads
Free Tech Magazines
Archives
Softwares
Newsletter
Suggest Us
Link to Us
 Asp.Net GridView Control with Multiple Filters
Posted by Moderator1 on 6/29/2007 10:18:56 AM Category: ADO.NET
Total Views : 32662
Add to my favorites
Email to friend
  
Introduction
This article explains the methodology of implementing multiple filters in an Ajax based Asp.Net GridView control. The main point to note down in this article is to filter the data within the GridView control.
Asp.Net GridView control is used to displays the values of a data source in a table where each column represents a field and each row represents a record. If you are familiar with the DataGrid control from the .NET Framework version 1.0, the GridView control is the successor to the DataGrid control. The GridView control enables you to select, sort, and edit records that get displayed from the data source. This article will give a brief knowledge to build a dropdown list filtering function within the GridView control. Additionally, we are going to implement AJAX into it.

Sample Scenario

For demonstration, let us take customer information to be filled in the GridView. We can build filters on all columns of the GridView, but for this demonstration, we just try to implement two types of filters one for the Gender and another for the Customer Type. For each filter we need to add DropDownList controls. The first DropDownList we are going to fill with static data and another we are going to fill with some dynamic content from the data source.

Set up the GridView Control

Open Microsoft Visual Studio 2005, create an Asp.Net Ajax Enabled Website, drag and drop an UpdatePanel, and drag and drop a GridView control from your Toolbox Data tab into the UpdatePanel.
  Change the value of AutoGenerateColumns of the GridView to false. Click on the SmartTag of the GridView, choose Add New Column, from the popup window to Add Field, add five TemplateFields in the GridView for Name, Gender, City, State and Customer Type. In each template field’s ItemTemplate section, add a Label Control and bind it to the corresponding field in the data source. The fields in our customer table are Cus_Name [Name of the Customer], Cus_Gender [Gender], Cus_City [City], Cus_State [State] and Cus_Type [Customer Type]. We are going to add DropDownList for the Gender and Customer Type column. So insert two DropDownList controls into the HeaderTemplate section of Gender and Customer Type column and name it as cmbGender and cmbCustomerType respectively.

Alter the AutoPostBack of the cmbGender DropDownList to True and since this dropdown has to contain static data, add ListItems such as All, Male and Female. Also add an event OnSelectedIndexChanged into it. So the structure of cmbGender will be as follows
<asp:DropDownList ID="cmbGender" runat="server" AutoPostBack="True" OnSelectedIndexChanged="cmbGender_SelectedIndexChanged">
<asp:ListItem Value="All">All</asp:ListItem>
<asp:ListItem Value="Male">Male</asp:ListItem>
<asp:ListItem Value="Female">Female</asp:ListItem>
</asp:DropDownList>

Now the cmbCustomerType control is going to hold dynamic data, so specify the DataTextField and DataValueField as Cus_Type. That is unique customer type data is going to fill in this DropDownList. Then make the AutoPostBack to True and add an event OnSelectedIndexChanged to do postback.

<asp:DropDownList ID=" cmbCustomerType" runat="server" AutoPostBack="True"
DataTextField="Cus_Type" DataValueField="Cus_Type"
OnSelectedIndexChanged="cmbType_SelectedIndexChanged">
</asp:DropDownList>

The first step in the code behind is to fill the cmbCustomerType control with unique dynamic data from data source and to retain its value on every postback. So we have to declare two page scope variables at the top of page to hold the DropDownList controls values.

protected string CustomerType;
protected string Gender;

These two variables will keep the value of the DropDownList on every postback. Now in the RowDataBound of the GridView control, we have to write a small block of code to fetch data from database and fill the cmbCustomerType control.

if (e.Row.RowType == DataControlRowType.Header) {
DropDownList cmbCustomerType = (DropDownList)e.Row.FindControl("cmbCustomerType");
cmbCustomerType.DataSource = FetchUniqueCustomerType();
cmbCustomerType.DataBind();
cmbCustomerType.Items.Insert(0, new ListItem("All", "All"));
cmbCustomerType.SelectedValue = CustomerType;

DropDownList cmbGender = (DropDownList)e.Row.FindControl("cmbGender");
cmbGender.SelectedValue = Gender;
}

The method FetchUniqueCustomerType should return the records with unique customer type information. You can write this method’s definition in some class file.

Now we need to fill the GridView with records from the database. To achieve this we are going to write a new method called BindGridView. The code block is given below
private void BindGridView() {
DataView dv = GetAllCustomers();
string condition = null;

if (GridView1.HeaderRow != null)
{
  DropDownList cmbCustomerType=(DropDownList)GridView1.HeaderRow.FindControl("cmbCustomerType");
  CustomerType = cmbCustomerType.SelectedValue;

  DropDownList cmbGender = (DropDownList)GridView1.HeaderRow.FindControl("cmbGender");
  Gender = cmbGender.SelectedValue;
  if (cmbCustomerType.SelectedValue != "All")
  {
    condition = "Cus_Type='" + cmbCustomerType.SelectedValue + "'";
  }

    if (cmbGender.SelectedValue != "All") {
      if (condition!= null)
        condition += " and Cus_ Gender ='" + cmbGender.SelectedValue + "'";
    else
        condition = "Cus_ Gender ='" + cmbGender.SelectedValue + "'";
     }
}


if (condition!= null)
   dv.RowFilter = condition;

GridView1.DataSource = dv;
GridView1.DataBind();
}
If you closely look at the above code once, you can easily understand the logic behind that. We are binding the GridView Control by a method which returns a DataView, then by consuming the values from the DropDownList, we construct a conditional string, then we do filter in the records of the DataView.

 
Point-by-Point Explanation

1. The method GetAllCustomers returns some records from the database and its return type is DataView.

DataView dv = GetAllCustomers();
2. Declare a variable to construct conditional string to do filter in the DataView.

string condition = null;
3. Checking if HeaderRow Exists for the GridView, else it will raise an exception.

if (GridView1.HeaderRow != null) {}


4. Find both DropDownList controls in the HeaderRow and assign its value to the variables to retain the value after every postback you made during filtering.
  DropDownList cmbCustomerType=(DropDownList)GridView1.HeaderRow.FindControl("cmbCustomerType");
  CustomerType = cmbCustomerType.SelectedValue;

  DropDownList cmbGender = (DropDownList)GridView1.HeaderRow.FindControl("cmbGender");
  Gender = cmbGender.SelectedValue; 
5. Next we building the expression with both DropDownList control’s SelectedValue and check if SelectedValue is ‘All’, then no need to construct it in the expression.
  if (cmbCustomerType.SelectedValue != "All")
  {
    condition = "Cus_Type='" + cmbCustomerType.SelectedValue + "'";
  }

    if (cmbGender.SelectedValue != "All") {
      if (condition!= null)
        condition += " and Cus_ Gender ='" + cmbGender.SelectedValue + "'";
    else
        condition = "Cus_ Gender ='" + cmbGender.SelectedValue + "'";
     } 
  }
6. If the string condition is not empty then we do filter in the DataView and then assing to the GridView control, which will display the available records only.

  if (condition!= null)
   dv.RowFilter = condition;

GridView1.DataSource = dv;
GridView1.DataBind();

Since this GridView control is placed inside an UpdatePanel, filtering records will be functioned in AJAX based without any postback.

Friends, here we provide only the basic logic to build Multiple Filters in a GridView. These can differ from application to application and from requirment to requirement. It is upto you READERS, to modify the code and apply the logic your application required.
 
To view our sample GridView with Multiple Filters, click here.
 
 
Viewer's Comments
Posted by tilak on 7/30/2007 2:31:36 PM
Hai It's very much interesting article, i have one dought,please clarify,that's like i--i have two dropdownlist boxes and 2 text boxes,one button and one grid view,in the two drop down list boxes we need to display the Category and Items data when page loads,next about text boxes i.e-we need to display quantity and amount , when we select category-category name(data-tablet) and Item(data-saridon)and qty,amount ,next click add(button) ,it'll save in the grid view (
 
Posted by Roger K on 8/15/2007 8:12:06 AM
This is an Excellent - can you post the project ( the source code of the project ) pl - it will be a BIG help. Thanks.
 
Posted by Henry on 8/25/2007 10:42:26 AM
can you post the project ( the source code of the project ) pl
 
Posted by Susan on 9/4/2007 3:07:57 PM
Is there a way to implement selecting multiple rows from a grid view or a datagrid? There is a need to do this, but I could not come up with any idea about this except maybe AJAX. Thanks
 
Posted by peter on 9/4/2007 5:15:27 PM
can you please post a source code for this example?
 
Posted by Jeff on 10/3/2007 9:17:06 PM
Thanks.
 
Posted by hilde on 10/16/2007 3:42:50 PM
Hi, the article is very good. I've tried to follow your examples but using 3 dropdown filters. No success yet... Could you please post a source code??
 
Posted by Richard on 10/31/2007 8:50:03 AM
Do you have any idea how useless an article like this is without the author taking just 1 minute to zip up the source project folder and post it with the article? Would it really hurt that much? As a developer, I am sure you understand the concept of time - and hate having to rewrite something that has already been written! :( Look at all the people asking the same - listen to your readers...
 
Posted by Christine on 11/6/2007 10:43:44 AM
Can you send the project for me? This article is very useful for me. But I can't let the Dropdownlist in the head row works fine. Please!
 
Posted by Elias Escobar on 11/20/2007 1:00:30 PM
May you send me the project please?....very handy Thank you
 
Posted by Adrian on 12/2/2007 12:33:33 AM
Hello guys, and thank you very much to the article's author for the example, it is exactly the same thing I have been trying to achieve... has any of you gotten to make it work? I haven't :( Best regards to all,
 
Posted by Faheem Ahmad on 12/6/2007 1:07:53 AM
Very interesting and helpful. Kindly keep it up.
 
Posted by pbk on 1/3/2008 6:17:26 AM
Very Goog one bht the thing is Do you have any idea how useless an article like this is without the author taking just 1 minute to zip up the source project folder and post it with the article? Would it really hurt that much? As a developer, I am sure you understand the concept of time - and hate having to rewrite something that has already been written! :( Look at all the people asking the same - listen to your readers...
 
Posted by srinivasa reddy on 1/18/2008 3:21:04 AM
my problem is i have one gridview in that i have multiple dropdownlists and textboxes and i have one button outside the gridview, after enter the all values the data will goes to the database and shows in the gridview............... that is problem pls help me ok pls send me code to my mail. thank u sir....................
 
Posted by Travis on 2/15/2008 4:52:11 PM
This article is needed but doesn't provide enough information to be ANY use to me. You are a tease sir. Please post the source code or remove your article so I (and other students) won't see it in a search result. Thanks
 
Posted by jithendar on 2/22/2008 5:29:18 AM
Can u explain me were you are using these varaibles protected string CustomerType; protected string Gender;
 
Posted by jithendar on 2/22/2008 5:31:35 AM
if (e.Row.RowType == DataControlRowType.Header) { DropDownList cmbCustomerType = (DropDownList)e.Row.FindControl("cmbCustomerType"); cmbCustomerType.DataSource = FetchUniqueCustomerType(); cmbCustomerType.DataBind(); cmbCustomerType.Items.Insert(0, new ListItem("All", "All")); cmbCustomerType.SelectedValue = CustomerType; DropDownList cmbGender = (DropDownList)e.Row.FindControl("cmbGender"); cmbGender.SelectedValue = Gender; } were i want to write this code
 
Posted by maurizio on 3/1/2008 12:03:13 PM
good idea..i will try...just a question.. if u have some colums good for sort and u press the header u loose the filter? ciao maurizio
 
Posted by maurizio on 3/3/2008 10:54:47 AM
a question..what we must code in OnSelectedIndexChanged="cmbType_SelectedIndexChanged ???? grazies maurizio
 
Posted by jithendar on 3/8/2008 2:37:25 AM
can u mail the full code
 
Posted by Adnan on 3/21/2008 12:19:12 AM
The form could get really busy with code if you had to create filter for each column. Why can't you approach this with customizable columns or some dynamic filters so you turn on filter on any column just by typing ShowFilter=true or something.
 
Posted by k on 4/12/2008 6:07:07 AM
k
 
Posted by l on 5/1/2008 10:31:36 AM
Still looking for that code
 
Posted by G on 5/1/2008 10:33:23 AM
This article is very helpful, but as a newbie I would really appreciate the full code to follow. Any way I can get it?
 
Posted by Ajay Sadyal on 5/29/2008 3:59:34 AM
it good but,give the images of all steps with it/ thank you!
 
Posted by babita on 6/5/2008 3:33:39 AM
hi plz tell m hw to pick crosspondance data from xml file and hw to bind with dropdownlist
 
Posted by Aaron on 6/12/2008 11:36:01 AM
Any update on getting the source code for this? Man would it help a lot!!!!!
 
Posted by rtg on 6/24/2008 5:00:19 AM
retsryyyyyyyyyyyyyyyyyyyyyyyyys
 
Posted by May Su on 6/30/2008 1:43:11 AM
Very nice. I would like to get the source code of this example.