Well, I have GridView with editable field like ‘TemplateField’ with DropDownList.
My code:
<Columns>
...
<asp:TemplateField SortExpression="Room" HeaderText="Room">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" Runat="server" DataSourceID="categoryDataSource" DataTextField="RoomNumber" DataValueField="RoomNumber" SelectedValue='<%# Bind("Room") %>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<ItemTemplate>
<asp:Label Runat="server" Text='<%# Bind("Room") %>' ID="Label1"></asp:Label>
</ItemTemplate>
</Columns>
My DB has table Rooms, which has rows: RoomId, RoomNumber.
In my DropDownList I try set all values from table Rooms.
Table has 3 rows (RoomId, RoomNumber): 1 – 20; 2 – 12; 3 – 24.
But write follow error:
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Maybe anybody know where have I erred?
Edit: Here is the SQLDataSource code
<asp:SqlDataSource ID="categoryDataSource" Runat="server"
SelectCommand="SELECT [RoomId], [RoomNumber] FROM [Rooms] ORDER BY [RoomNumber]"
ConnectionString="Data Source=.\MSSQLSERVERR2;AttachDbFilename=|DataDirectory|\ARMDB.MDF;Integrated Security=True;User Instance=True">
</asp:SqlDataSource>
The error indicates that the value that you are trying to set as selected into the drop-down list does not exist. I believe that this has happen mostly because not choosing a wrong field for value in drop-down list or setting wrong value.
For example, in your case, most probably, you are storing RoomId (and not RoomNumber) in the referenced table, so you need to bind value field of drop-down list accordingly
Note DataValueField value – its RoomId and not room number. (Assuming
Bind("Room")is going to return room id)