This is by no means revolutionary, but I tell you, I just never took the time to centralize this code. Each time I had to write it out for each DropDownList made me sicker and sicker.
What I can say in my defense, and I bet many developers will agree, is that I have way too many things to do, seem to always be running behind, and there always seem to be something stupid in my code I never took the time to do properly.
I feel so much better now that I took all 3 minutes to write this. Whew!
public static void SelectListItem(DropDownList dropDown, string selectedValue, string defaultValue) { if (dropDown.Items.FindByValue(selectedValue) != null) dropDown.Items.FindByValue(selectedValue).Selected = true; else { //SBE 12/25/2004: if no default passed in, don't select anything if (defaultValue == null) return; if (dropDown.Items.FindByValue(defaultValue) != null) dropDown.Items.FindByValue(defaultValue).Selected = true; else throw new ApplicationException("'" + defaultValue + "' item doesn't exist in " + dropDown.ID.ToString()); } }