ASP.Net DropDownList - Robust

Setting up DropDownList control to accomodate invalid values.

Does your dropdown control return messages like

DropDownList has a SelectedValue which is invalid because it does not exist in the list of item

Here’s an example of how to fix this

1
2
3
4
5
6
7
8
9
10
11
12
13
<asp:DropDownList 
ID='ddl_Edit_codesLicensesAndCertsId'
runat='server'
cssClass='form-control'
DataSourceID='ods_codesLicensesAndCertsId'
DataTextField='description'
DataValueField='id'
SelectedValue='<%#Bind("codesLicensesAndCertsId")%>'
AppendDataBoundItems="true"
OnDataBinding="ddl_Edit_codesLicensesAndCertsId_DataBinding"
>
<asp:ListItem Value="" Text="Select"></asp:ListItem>
</asp:DropDownList>

I added AppendDataBoundItems, OnDataBinding, and an extra ListItem

Then I created the OnDataBinding function

1
2
3
4
5
6
7
8
9
Protected Sub ddl_Edit_codesLicensesAndCertsId_DataBinding(sender As Object, e As EventArgs)
Dim ddList As DropDownList = CType(sender, DropDownList)
RemoveHandler ddList.DataBinding, AddressOf ddl_Edit_codesLicensesAndCertsId_DataBinding
Try
ddList.DataBind()
Catch ex As ArgumentOutOfRangeException
ddList.SelectedValue = "" ' or whatever value you have for the page dropdownlist
End Try
End Sub

References:
https://blogs.uw.edu/earnshaw/2015/02/18/selected-value-invalid/