piątek, 5 marca 2010

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

Enviroment: You've got a FormView or some other data control which displays single item and allows edit it. In edit mode there's a dropdown list with available names that user can select value from. Then when user wants to edit a person the underlaying data for selecting name has changed and has no more an item with value for edited person. (This can happen when for example someone deletes a name record directly in the db) That situation will cause "dropdownlist has a SelectedValue which is invalid because it does not exist in the list of items" error being thrown, because we've binded dropdownList.SelectedValue to an item which isn't in db any more. The workoround is to delete SelectedValue binding in aspx code and and handle unexpected situation in FormView_PreRender event. Here's a code for that:
protected void FormView1_PreRender(object sender, EventArgs e)
    {
        if (FormView1.CurrentMode == FormViewMode.Edit)
        {
            DataRowView rowView = (DataRowView)(FormView1.DataItem);
            DropDownList ddlNames = FormView1.FindControl("ddlNames") as DropDownList;
            bool isItemStillThere = ddlNames.Items.FindByValue(rowView["NameID"].ToString()) != null;
            if ((rowView != null) && isItemStillThere)
            {
                ddlNames.SelectedValue = rowView["NameID"].ToString();
            }
        }
    }
The aspx code:
 
Test website:

Brak komentarzy: