开发者

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

开发者 https://www.devze.com 2022-12-17 06:23 出处:网络
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 开发

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?


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.


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


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;
}


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号