'Why is drop-down list throwing an error on binding?

I am trying to populate a drop-down list when some specific condition changes. This is working fine 99% of all cases. But once in a while, I get this error on our production server:

Exception of type 'System.Web.HttpUnhandledException' was thrown.; 'ddlNCE' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value;

We are unable to replicate this in our development environment. This is the call stack:

at System.Web.UI.WebControls.ListControl.PerformDataBinding(IEnumerable dataSource)
at System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e)
at System.Web.UI.WebControls.ListControl.PerformSelect()
at SeqClass.FillDDL(DropDownList aList)
at operations.BindEventDataDDLs()
at operations.SetFilterPanels()
at System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventA...

Here is the simplified function that binds the drop-down:

Public Shared Sub FillDDL(aList As DropDownList)
    aList.Items.Clear()
    aList.ClearSelection()

    aList.DataTextField = "TextColumn"
    aList.DataValueField = "ID"
    aList.DataSource = DAL.GetDataTable("Select ID,TextColumn From MyTable Order By TextColumn")
    aList.DataBind()
    aList.Items.Insert(0, New ListItem("-- Select Item --", String.Empty))
End Sub

The list as well as the selection is being cleared before Databind is called. Does anybody have any idea why this error occurs randomly on our production server?



Solution 1:[1]

In my case we have a list of "items" a user can choose from and store in their "cart". To this end, we have a repeater with, among other things, a dropdown list bound to a list of available options.

That said, the user can make his selections, select his options and save to his cart.

The situation that arises & causes the error is: later the user returns, pulls up his cart. Maybe his selection is no longer available in the list of options that's currently available. In the front end, we're declaratively binding not only the list of available options for the dropdown, but also the SelectedValue. When the SelectedValue doesn't exist in the list of currently available items, we get the error during databinding.

The solution in this case was to not declaratively bind the selected item but handle the OnDataBound Event of the repeater and try to set the SelectedValue of the dropdown there - where we easily check for the existence of the previously selected item before we set it, and handle as we see fit when it doesn't exist.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xcr