Clearing all items in a List Control

I am currently working on an ASP.NET project where the client needs to have a web form with about ten lists, each list containing anywhere from three or four to a couple of dozen options.

These lists are composed as a CheckBoxList, RadioButtonList or DropDownList, all based on the standard <asp:xxxList> control.

The selected items in the lists are used to build a Linq statement to query and filter a large database table. The (concept) UI of these lists are like the image below.

Clearing the list

In order to begin a new query, we figured it would be handy to have a button below each list to clear the selection of all items instead of manually deselecting every option. So I added a Clear button ('Leegmaken' in Dutch) and wrote the following code for the button. Sure, I looked through the Intellisense list for something like 'empty', or, 'deselect', but couldn't find anything.

So I assumed this was the easiest way to set the Selected state of every ListItem to false. Have a foreach() loop and loop through every ListItem in the control, setting the Selected property to false. (The bindConditionalGrid() method below the loop is for binding the GridView in the page again, to reflect the new criteria.)

Until yesterday.


By accident I was looking at the Intellisense list for a CheckBoxList control, when I stumbled upon the ClearSelection() method, which apparently had the exact same function as the little method I wrote above!

So now instead of four lines of code, I need only one. And this times ten, for the number of Clear-buttons in the page (I know, I think it is possible to write a generic method to clear a list and pass the button name or list name as a parameter, but this quick and dirty approach is suitable for now. If you have such a method, feel free to share it via a comment below :-).

Here is the MSDN page with the documentation for the ClearSelection method:



Intellisense is your friend.

There might be prewritten methods for a task that you wish to accomplish. They might have other names than you expect :-), especially when English is not your mother tongue.

Peter Kassenaar
-- 27 juni 2008

Reacties zijn gesloten