views:

162

answers:

2

I have an ASP.Net form where I use a DropDownList control to display data retrieved from a table. However setting the SelectedValue of the DropDownList to a value not existing in the dropdown list does not trigger an exception.

Try
    dropDownList.SelectedValue = value
Catch ex as Exception
    Throw
End Try

In the code above, if I assign a value that does not belong to the list's item, it does not throw an Exception. It just selects the first item in the list when the HTML is rendered.

Any ideas why?

By the way, I have a blank (String.Empty) item as the first item in the list. I also used DataBind() to bind the listItem to a DataTable. Does that make any difference?

+1  A: 

When the selected value is not in the list of available values and a postback is performed, an ArgumentOutOfRangeException is thrown:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue.aspx

Chris Haas
Thanks. But I need to check if the data I got from the database belongs to the list on initial page load.
Devmonster
Sorry, I was responding to why it doesn't throw an exception. For your solution you're going to have to check the dropdownlists's Items propery, maybe using the Contains method. Me.ComboBox1.Items.Contains()
Chris Haas
I rewrote my code to check whether the item exists in the Items property. What about Me.Dropdown.Items.FindByValue()? Do you recommend it?
Devmonster
Yep, totally use that. I was looking at a WinForms ComboBox which I assumed had the same methods on the collection and Contains() was the best one that it had. FindByValue() is much better.
Chris Haas
A: 

Thanks guys for answering. What I ultimately did was used the FindByValue() method of the Dropdownlist and see if the value exists in the list:

If Not DropDownlist.Items.FindByValue(value) Is Nothing Then
    ' do what the Exception is supposed to do '
Else
    DropDownList.SelectedValue = value
End If

The FindByValue() returns Nothing if the passed parameter does not belong to the list. I avoided using an Exception (which is heavy on processing) as a way to trap the problem, and it works exactly as I needed.

Devmonster