views:

437

answers:

4

RE-POSTING WITH MORE ACCURATE DATA:

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 2 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 after the DataBind operation executes is the ID value from the first row in the data
6) This exception happens the very first time this code is executed after a fresh page load<>


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

Change the first two line with this :

listOrgs.SelectedItem.Selected = false; 
listOrgs.Items.Clear();
Canavar
Setting SelectedItem.Selected = false throws an exception
Bob Jones
What is the exception ? maybe you should instantiate your dropdownlist again before binding : listOrgs = new DropDownList();
Canavar
+1  A: 

Try setting listOrgs.SelectedValue = "0" after you refresh the DataSource

At the moment you are trying to select the first item in an empty list.

ChrisF
That had on effect.
Bob Jones
A: 

In case you still have this problem this is how i resolved it:

listOrgs.SelectedIndex = -1;    // Clears the SelectedIndex to avoid the exception
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName"; 
listOrgs.DataValueField = "OrganizationID"; 
listOrgs.DataBind();            //Unless you have "listOrgs.AppendDataBoundItems = true" you don't need to clear the list
PMarques
+2  A: 

Apparently the solution I posted wasn't entirely effective... Eventually in my application I changed to this:

listOrgs.Items.Clear();
listOrgs.SelectedIndex = -1;
listOrgs.SelectedValue = null;
listOrgs.ClearSelection();     // Clears the selection to avoid the exception (only one of these should be enough but in my application I needed all..)
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName"; 
listOrgs.DataValueField = "OrganizationID"; 
listOrgs.DataBind();
PMarques
This is the only solution that worked for me. I never realized how horrible the stock ddl is
Mario