24 Feb

Filter GridView by DropDownList

In the post How to Display SharePoint List Data in a GridView, we looked at how to use a SPQuery object to filter the items from a SharePoint list. You can enable the user to select the filter value using a form control in the web part.

using a form control in the web part
I added a new column called ‘Class’ to the list. When the user selects a Class from the dropdown, the page reloads with only animals from that Class.
Filter GridView by DropDownList - 03

(1) Create a Separate Function for Loading the GridView

I simply moved the code for loading the GridView out of the Page_Load() event and into another function, which accepts a string parameter for the filter value. I also added the code to display the new column, ‘Class’. I’ve simplified the code from the previous post, but the code from the previous example will work too.

Next, for your SPQuery, add an if statement that adds the WHERE clause if a filter value has been passed in to the function.

(2) Add a DropDownList Control

This is pretty straightforward; just add a DropDownList control and its ListItems to the ACSX file. For the control, include an OnSelectedIndexChanged event, and set AutoPostBack to true.

(3) Fill in the SelectedIndexChanged event

When the DropDownList value changes, pass the new selected value to the GridView as a filter value.

If you want the entire list to load when the user first hits the page, just add the function to the Page_Load event.


Copyright © 2014 Keren Apura; Fruitful theme by fruitfulcode