Quantcast
Channel: naspinski - steal some code
Viewing all articles
Browse latest Browse all 15

Extensions for simplifying DropDownList interaction

$
0
0

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:
DropDownList1.Set("some_value");

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'
  try
  { 
    ddl.SelectedIndex = ddl.Items
     .IndexOf(ddl.Items.FindByValue(findByVal)); 
  }
    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:
DropDownList1.RemoveItem("Any");

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.

Viewing all articles
Browse latest Browse all 15

Trending Articles