views:

299

answers:

2

I encounter this problem repeatedly, and haven't a clue what is causing it. I get an exception in the DataBind: "SelectedValue which is invalid because it does not exist in the list of items". Here are some important pieces of information:

1) I reload listOrgs periodically when the underlying data has changed. 2) The Organization.DTListAll call returns about 500 Int, String pairs. 3) There are no duplicate or null values in the returned data 4) After the first two lines below, listOrgs.Items.Count is 0, and the Selected Value is 0 5) The selected value when the DataBind operation executes is a value that is not in the set of ID values returned 6) All of the stuff I have found on line so far hasn't helped. 7) I am stumped!

listOrgs.Items.Clear(); listOrgs.SelectedValue = "0"; listOrgs.DataSource = new Organization().DTListAll(SiteID); listOrgs.DataTextField = "OrganizationName"; listOrgs.DataValueField = "OrganizationID"; listOrgs.DataBind();

Bob Jones

A: 

the value that would be put into the dropdown is not in the table/source where the values are pulled from, so it gives an error. I get the same thing, I know why but I don't know how to get around it. Did you have any luck fixing this?

John Deverdits
A: 

Check for an existing value

    this.DropDownList1.Items.Clear();
    //--dont use this:
    //this.DropDownList1.SelectedValue = "0";
    DataTable dt = new DataTable();
    dt.Columns.Add("x", typeof(System.Int32));
    dt.Columns.Add("xs", typeof(System.String));
    for (int x = 0; x < 100; x++)
    {
        DataRow dr = dt.NewRow();
        dr["x"] = x;
        dr["xs"] = x.ToString();
        dt.Rows.Add(dr);
    }
    DropDownList1.DataValueField = "x";
    DropDownList1.DataSource = dt;
    DropDownList1.DataBind();
    // check for existing value:
    int valueToCheck = 99; // last item
    if (this.DropDownList1.Items.FindByValue(valueToCheck.ToString()) != null)
    {
        this.DropDownList1.SelectedValue = valueToCheck.ToString();
    }

Besides that - you might want to try to set the datatext and datavalue fields before you bind (afaik that is a performance++)

riffnl