Devmonster
Devmonster

Reputation: 709

ASP.NET Setting SelectedValue that doesn't belong to the list does not trigger Exception

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?

Upvotes: 2

Views: 8925

Answers (4)

Yusuf Mohammad
Yusuf Mohammad

Reputation: 69

you can use this method for easy to set SelectedValue

    private void DropDownSelectSafeValue(this DropDownList Drp, string Value) {             
        if (Drp.Items.FindByValue(Value) == null)
            Drp.SelectedValue = Value;
}

Upvotes: 0

Alex
Alex

Reputation: 1

I think the NOT should be removed. Otherwise, it's the reverse. This is what I did.

If ddAssignedDTL.Items.FindByValue(sqlreader("C_AssignedDTL").ToString) Is Nothing Then

 ' do what the Exception is supposed to do '
 ddAssignedDTL.Items.Add(New ListItem("<Invalid DTL-" & sqlreader("C_AssignedDTL").ToString & ">", sqlreader("C_AssignedDTL").ToString))
 ddAssignedDTL.SelectedValue = sqlreader("C_AssignedDTL").ToString
 DTL = sqlreader("C_AssignedDTL").ToString
 ddAssignedDTL.BackColor = Drawing.Color.Red
Else
 ddAssignedDTL.SelectedValue = sqlreader("C_AssignedDTL").ToString
 DTL = sqlreader("C_AssignedDTL").ToString()
End If

Upvotes: -1

Devmonster
Devmonster

Reputation: 709

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.

Upvotes: 9

Chris Haas
Chris Haas

Reputation: 55447

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

Upvotes: 4

Related Questions