Extensions for simplifying DropDownList interaction

Extensions for setting the selected value and removing an item from DropDownLists

I love extensions, they make my life so much easier. Simple things that I can do in a coupole lines of code, I now do in even fewer thanks to my almighty extensions. Here are a couple of super simple ones for easy interaction with DropDownLists

setting the selected value

Sometimes it is a pain to set the selected value of a DropDownList, if it is there, it works fine, but if not, it is a pain in the butt. Here is what I use to set mine:

It's just that easy, and if it's not in the ddl, it will work just as well. Here is the extension code:
public static void Set(this DropDownList ddl,
 string findByVal)
{ // attempts to set a DDL to the 'findByVal'
    ddl.SelectedIndex = ddl.Items
    catch { };

removing an item

Once again, we all know the code for this, but an extension makes it easier, and also hanldes it if the item is not there:

And the code:
public static void RemoveItem(this DropDownList ddl, 
 string item)
  try { ddl.Items.Remove(ddl.Items.FindByText(item)); }
  catch { }

Normally I discourage a blank catch{} but in this case, the only error you would be encountering is if the item is not there, so unless you are worried bout that, you should be fine.
Comments are closed