Sunday, September 24, 2006
« DAMN - Developers Advocating More Naps :... | Main | DAEMON Tools 4.06 Released Today »

In doing a little ASP.NET 2.0 databinding to a DropDownList control I was presented with a nice little error:

"'[ddlcontrolname]' has a SelectedValue with is invalid because it does not exist in the list of items. Parameter name: value"

Well, this is occurring on a postback for one DropDownList on a requery of a dependent DropDownList.  In other words, DDL01 performs an autopostback which forces DDL02 to requery its list.  The error is occurring because the SelectedValue that was originally bound to DDL02 is no longer in the set of data now associated with it.

You might try, as I did, to work around this by setting the SelectedValue property to null or string.Empty prior to rebinding, but that didn't seem to work for me.

There is a very easy solution to this dilemma, however.  In my case, all I had to do was clear the list, then set SelectedValue to null, then rebind as the following method does:

private void bindToList(DropDownList ddl, DataSet ds, string textFieldName, string valueFieldName) {
   // clear out any previous selection to avoid the ugly IndexOutOfRangeException
   ddl.Items.Clear();
   ddl.SelectedValue = null;

   // perform databinding as normal
   ddl.DataSource = ds;
   ddl.DataTextField = textFieldName;
   ddl.DataValueField = valueFieldName;
   ddl.DataBind();
}