Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 495
Bob Jones Avatar asked Sep 04 '09 19:09

Bob Jones


People also ask

What has a SelectedValue that is invalid because it does?

'DropDownList' has a SelectedValue which is invalid because it does not exist in the list of items. As it is possible for the user to change the values of the list (in a codetable) it is possible that an earlier selected item not exists anymore.


3 Answers

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();
like image 180
PMarques Avatar answered Oct 16 '22 13:10

PMarques


I kept getting this error.
Weird thing is that before I set the datasource and rebind after deleting an item the selected index = -1.

If I explicitly set the selectedIndex = -1; then it works and doesn't throw an error.

So even though it was already -1 setting it to -1 stops it from erroring.

Weird eh?

like image 8
DazManCat Avatar answered Oct 16 '22 14:10

DazManCat


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.

like image 3
ChrisF Avatar answered Oct 16 '22 12:10

ChrisF