scrot
scrot

Reputation: 1647

SelectedValue is invalid - doesn't exist in list - C#/ASP.NET

Exception is: 'Country' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();

The values held within dsCountry.tblDropDownValues are:

Id                                      AttrValue       AttrName
aefa28e0-a118-11dd-ad8b-080c210c9a66    PLEASE SELECT   Country
213a743e-ea0b-419c-bd44-03b1c35241b3    USA         Country
eefa1387-8dc0-11d8-975f-13da67a41a5d    CANADA          Country

Upvotes: 1

Views: 1912

Answers (3)

AndyG
AndyG

Reputation: 41092

Every time I got this error it was because the keys I was matching on to bind my data didn't match.

The lines you showed may not be the problem. Look into when you are possibly loading a record from another table and binding their values into the dropdown list.

For example, if you have a dropdown list on your page that contains all your country names with country Ids as Value-behinds These values are all stored in a table CountryTbl. You also have a grid on the page where a user can select which record from another table they want to edit. Let's say this record contains Information like Name, Phone #, and Country, and its all stored in another table UserTbl. When the form is attempting to bind its data from UserTbl, it is trying to set your Country DropDownList equal to a bound value from UserTbl.

But what can happen, and has happened to me many times, is that you have bad data in your UserTbl like a Country that doesn't exist anymore, or another value in its Country field that just doesn't match any of your values in the Country Dropdown.

Look into your database tables and see if you have any CountryIds in your "UserTbl" that don't match any of the ContryIds in your "CountryTbl".

Upvotes: 2

Ken Ray
Ken Ray

Reputation: 2528

This could also be caused by having nulls in the source data you are binding to your drop down list.

Upvotes: 0

Jay S
Jay S

Reputation: 7994

Try binding the data on postback. It sounds like when the event handler is accessing the DropDownList, it hasn't been repopulated with the values you are initially binding to the DropDownList.

Also, remember to bind early enough so that it is bound before the event handler starts its processing. OnInit or OnLoad should be good enough.

Otherwise, might need some more details:

  1. When is the exception occurring? During the rendering, or on the postback in the event handler?
  2. Do you have a stack trace on the error that might point to the point in the code where the selected value is accessed?
  3. When are you binding the data?

Upvotes: 2

Related Questions