loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Extensions for simplifying DropDownList interaction

by naspinski 6/10/2009 12:03:00 PM

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.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

asp.net | c# | steal some code

Related posts


Comments are closed