Selecting a List Control Item Utility Method
I think every developer/team should have a good set of utility functions to help make code cleaner and easier to maintain. Typicaly these are methods that probably should be in the core framework for us to use, but somehow the framework team never got around to it. The first method I am going to talk about is one I use multiple times on every site and often multiple times on any given page, SelectListControlItem.
Public Sub SelectListControlItem( _
ByRef dl As System.Web.UI.WebControls.ListControl, ByVal mValue As Object)
If IsNothing(dl.Items.FindByValue(mValue.ToString)) = False Then
dl.Items.FindByValue(mValue.ToString).Selected =TrueEnd IfEnd Sub
This is a pretty simple method, but accomplishes a very common task and can be used for multiple controls, like the drop-down list, radio button, list box, etc. It would not be ideal for a check box list, but that can be another method. I really built this method a few years ago to help me select states in that common drop-down. I have eventually evovled it to cover related controls.
It is pretty simple, I have found you want to clear any selection you may already have or you will toss an error. Next see if you have an item with the Value property equal to the value you want to select and select it. I chose to pass an object as the value type so it will handle strings, booleans, integers and just about anything else I could pass. I bury this method in my base page class that I inherit all my production pages from. This method has been a true time saver over the years.