Tuesday 6 March 2007

Error on DataBind() of DropDownList:, invalid SelectedValue

Getting error:

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


The SelectedValue before the databind is set to "" (i.e. blank string)
The error occurs because the data being bound does not include a value of "" (blank string).

To fix it:
  1. Set AppendDataBoundItems=true for control
  2. Clear the list prior to databind; .Items.Clear();
  3. Add a blank item: .Items.Add(new ListItem("", ""));
  4. Call .DataBind();