Search code examples
c#asp.netgridviewdata-bindingsqldatasource

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


I'm using TemplateField in GridView to implement edit/delete from database.

I'm Querying Data with the SqlDataSource Control.

when I edit the Table from page I get following error:

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

This is due to the data from dB is not matching any of the DropDownList Country name.

I understand the problem from this question (solution is not given there!)

I think when I insert data to dB, it automatically adds redundant spaces to data(like name of country)

So, one solution is to remove the spaces (Trim) from String so that value get matched in one of the DropDownList items.

because <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Eval("Country")%>'
doesn't match any list item of DropDownList

but

<asp:DropDownList ID="DropDownList1" runat="server"  SelectedValue='<%# Eval("Country").ToString().Trim()%>'>

matches the list item of DropDownList.

Now I want to update the data back to the database but instead of country name null value get stored. (I think it is the limitation of Eval())

I can update the data back to the dB using Bind() but Bind doesn't support ToString().Trim() so I can't trim the string to match one of the items from DropDownList.

How can I update back the data to dB?

my raw code


Solution

  • After scratching my head for several hours, finally, I found the elegant solution for the trailing spaces problem.

    In my Table definition, In Country field definition I was using nchar(100) instead of nvarchar(100). The former always has 100 characters (thus the trailing spaces), the later can have up to 100 characters, but doesn't fill up the space (thus matches the item in DropDownlist).

    In nutshell, <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("Country")%>'> is working fine now.

    I hope it helps future readers.