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.
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.
(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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
protected void Load_Items(string filter) { SPWeb thisWeb = SPContext.Current.Web; SPQuery query = new SPQuery(); query.ViewFields = string.Concat( "<FieldRef Name='ID' />", "<FieldRef Name='Title' />", "<FieldRef Name='Class' />"); query.ViewFieldsOnly = true; //The list name is Sample List. SPList thisList = thisWeb.Lists["Sample List"]; DataTable dt = new DataTable(); dt = thisList.GetItems(query).GetDataTable(); GridView1.DataSource = dt; GridView1.AutoGenerateColumns = true; GridView1.DataBind(); } //end Load_Items |
Next, for your SPQuery, add an if statement that adds the WHERE clause if a filter value has been passed in to the function.
1 2 3 4 5 6 7 8 9 10 11 |
SPQuery query = new SPQuery(); if (filter != "") { query.Query = string.Concat( "<Where>", "<Eq>", "<FieldRef Name='Class' />", "<Value Type='Text'>", filter, "</Value>", "</Eq>", "</Where>"); } |
(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.
1 2 3 4 5 6 |
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="Filter_Items" AutoPostBack="true"> <asp:ListItem Text="(Select one to filter)" Value="" /> <asp:ListItem Text="Big Cat" Value="Big Cat" /> <asp:ListItem Text="Bear" Value="Bear" /> <asp:ListItem Text="Primate" Value="Primate" /> </asp:DropDownList> |
(3) Fill in the SelectedIndexChanged event
When the DropDownList value changes, pass the new selected value to the GridView as a filter value.
1 2 3 4 |
protected void Filter_Items(Object sender, EventArgs e) { Load_Items(DropDownList1.SelectedValue); } //end Filter_Items |
If you want the entire list to load when the user first hits the page, just add the function to the Page_Load event.
1 2 3 4 5 6 7 |
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Load_Items(""); } } //end Page_Load |