Filter Gridview via DropDownList & Search TextBox in ASP.NET
Have you ever developed one of those systems users just seem to love to use? I’ll admit its a good problem to have, yet they just pile on the records one-by-one until your small band-aid system starts to collapse under its own lack of usability. A few years back, I created a graphics manager program for the marketing crew to keep track of their myriad of buttons, banners and general digital assets. I let the graphics guys drop the image in the appropriate folder that corresponded to an image category then the management system sifted through those folders to show what was there. Simple right? Wrong. Three years later, it is a mess of mammoth proportions. You can’t find anything, and its almost not like having anything to manage these resources at all.
So I’ve decided to database all these resources by associating them with categories, keyword tags, image dimensions, and title/description. So the question becomes how to let the users sift through all these new fields without the interface getting bogged down in the clutter? The system’s default page is a gridview listing all the graphics that currently in the system. Along the top, I’ve place two dropdownlist controls and a TextBox control. The dropdownlists will allow me to filter the grid based on the category and/or dimensions of the control, and the textbox will allow me to do specific searches on a given term for even greater specification.
So lets take a look at the ASPX side of things. Below we have the GridView. I’ve cleaned up the code to focus on the essential elements. Nothing out of the ordinary here. Just your basic SqlDataSource feeding back the relevant fields to the GridView.
So if our ASPX is so plain Jane, where is all the fun happening? The codebehind of course. All the SelectIndexChanged and Search_OnClick functions reference the same method — parseFilters. Essentially we are doing the same thing whenever a user makes a selection.
parseFilters just does a survey to see what is in each field to build the conditional filter. Whenever one of these boxes is set to something other than the default, we tack that value onto sCondition. Once we’ve stepped through each possibility, we set the FilterExpression of our GridView’s SqlDataSource equal to sCondition.
That’s all there is to it. One hangup to be aware of. If the GridView comes back blank, it means that no selections met your search. If you are sure there are variables that should be getting served up, take advantage of that Response.Write of sCondition I have included to see what exactly is getting passed back to the Datasource. It can save you lots of time wrapping yourself in frustration.
Now you have a nice, simple way to drill down on your data so your users can find exactly what they are looking for with minimal effort.
