How to check if your drop down list contains a specific value using C#

If you want to set the default value of a drop down list from a value being passed to you by a third party you should always include a check to ensure that your drop down contains the value so that you don't end up with some nasty compiler errors.

To keep things simple let's say I want to check if my drop down contains the value "MyValue". If it does I want to pre-select that option for the user. To do this I would use something like below:

if (MyDropDownList.Items.FindByValue("MyValue") != null)
{
    MyDropDownList.SelectedValue = "MyValue";
}

You can also search based on the text value of your drop down by using FindByText instead of FindByValue.

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets