View Single Post
  #9 (permalink)  
Old March 13th, 2009, 02:58 AM
Lee Dumond's Avatar
Lee Dumond Lee Dumond is offline
Wrox Author
Points: 4,942, Level: 29
Points: 4,942, Level: 29 Points: 4,942, Level: 29 Points: 4,942, Level: 29
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jan 2008
Location: Decatur, IL, USA.
Posts: 923
Thanks: 12
Thanked 166 Times in 162 Posts
Default

I tried this on the Northwind sample database and it definitely works. This is the accepted way of doing this, trust me.

The reason you are getting this error is that you have Categories in the ID-Name-Category table that do not exist in the seperate Categories table. This could be due to a completely missing record, or even a slight typo.

Let's say you have this:

Code:
ID    Name          Category
============================
1     Bananna       Fruit
2     Ford          Car
3     Bagel         Bread
4     Apple         Fruit
5     Chevy         Car
6     Pepsi         Beverage
And let's say you have in your categories table:

Code:
Category
========
Fruit
Car
Bread
As the Gridview binds, everything will be fine up until record #6. Record number 6 will attempt to set the SelectedValue of the DropDownList to "Beverage", but it will fail because the DropDown list is bound the the Categories table, and thus contains only the Items Fuit, Car, and Bread. It cannot find a value of "Beverage" to set the SelectedValue to, and thus, it says:

Quote:
Hey! The value of category for this record is "Beverage", but the DropDownList that is supposed to represent that in the GridView has no item with a value of "Beverage", and thus, I cannot do SelectedValue="Beverage"!!!
Or, in computerese:

Code:
ArgumentOutOfRangeException: 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value
Look for this in your data, and you will be able to fix the problem.

After you do that, you should PREVENT this problem from happening by establishing a foreign key relationship between the two tables, and ONLY storing the IDs from Table 2 in Table 1. In other words:

Code:
ID    Name          CategoryID
==============================
1     Bananna       1
2     Ford          2
3     Bagel         3
4     Apple         1
5     Chevy         2
6     Pepsi         4
Code:
ID   Category
========
1    Fruit
2    Car
3    Bread
4    Beverage
By establishing a key relationship between the tables, you will never be able to store a CategoryID in Table 1 which does not already exist as a, ID in Table 2. Under that scenario, this error can never occur.

Hope this makes sense for you.
__________________
Visit my blog at http://leedumond.com
Follow me on Twitter: http://twitter.com/LeeDumond

Code:
if (this.PostHelpedYou)
{
   ClickThanksButton(); 
}