'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items RRS feed

  • Question

  • User-694414214 posted

    Friends being a newbie in asp.net I have been layin my hands on this problem for quiet sometime now...hope I find my answer here..

    First things first..

    I have a gridview which  is bound to a SQLDatasource1.In the gridview we have two dropdown(dropdownlist1 and dropdownlist2) Template fields.

    Now one of the template field is bound to a datasource SQL datasource2 while the other contains a list of data hardcoded.

    Now my requirement is to update the datasource bound to the gridview with the data selectd with the dropdownlist.

    Now the dropdownlist is bound to a column called vendorname contained in vendormaster table.

    The gridview is bound to a table called request which also contains a column called vendorname..however this column is empty..ie has no data in any row..simply ' '.........

    My requirement is to b able to update the request table by selecting values from the two dropdownlist in the gridview..instead i end up with this error...

    "'DropDownList2' has a SelectedValue which is invalid because it does not exist in the list of items"

    After going thru a few posts I understand that its due "no values" present in the "request" table for "vendormaster" column. 

    I then tried hardcodin the values for dropdownlist1 as i have for dropdownlist2..Interesting it now gives the same error for dropdownlist2....

    when i removed dropdownlist2 from the gridview things work abs fine....but guys I need to have both the dropdownlist and above that I need to bind my dropdwnlist1 to a datasource.......

    How do I accomplish this update....any help wll b highly apreciated..here is the part my code....... 


    ID="GridView1" runat="server" Style="left: 0px; ; top: -87px"

    Width="550px" AutoGenerateEditButton="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource2" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Height="190px">


    <asp:BoundField DataField="AssetName" HeaderText="AssetName" SortExpression="AssetName" />

    <asp:BoundField DataField="Units" HeaderText="Units" SortExpression="Units" />

    <asp:BoundField DataField="RequestDescription" ReadOnly="True" HeaderText="RequestDescription" SortExpression="RequestDescription" />

    <asp:TemplateField HeaderText="VendorName">


    <asp:DropDownList ID="DropDownList1" runat="server" Style="" Width="94px"/>

    <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:inventoryConnectionString %>"

    ' SelectCommand="SELECT [VendorName] FROM [VendorMaster]"></asp:SqlDataSource>




    <asp:TemplateField HeaderText="Status">


    ' <asp:DropDownList ID="DropDownList2" runat="server" Style="" Width="39px" selectedvalue='<%# Bind("Status") %>'>

    ' <asp:ListItem></asp:ListItem>

    ' <asp:ListItem Value="A"></asp:ListItem>

    ' <asp:ListItem Value="P"></asp:ListItem>

    ' <asp:ListItem Value="D"></asp:ListItem>

    ' </asp:DropDownList>

    ' </EditItemTemplate>






    <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:inventoryConnectionString %>" SelectCommand="SELECT [VendorName] FROM [VendorMaster]"></asp:SqlDataSource>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:inventoryConnectionString %>"

    SelectCommand="SELECT DISTINCT [OrderNumber] FROM [Requisition] WHERE ([Status] &lt;&gt; @Status)">


    <asp:Parameter DefaultValue="A" Name="Status" Type="String" />



    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:inventoryConnectionString %>"

    SelectCommand="SELECT [AssetName], [Units], [VendorName], [RequestDescription], [Status] FROM [Requisition] WHERE (([OrderNumber] = @OrderNumber) AND ([Status] &lt;&gt; @Status))"

    UpdateCommand="UPDATE [Requisition] SET [Units]=@Units,[VendorName]=@VendorName,[Status]=@Status WHERE (([OrderNumber] = @OrderNumber) AND ([AssetName] = @AssetName))">


    <asp:ControlParameter ControlID="DropDownList1" Name="OrderNumber" PropertyName="SelectedValue"

    Type="Int32" />

    <asp:Parameter DefaultValue="A" Name="Status" Type="String" />



    <asp:ControlParameter ControlID="DropDownList1" Name="OrderNumber" PropertyName="SelectedValue"

    Type="Int32" />


    <asp:Parameter Name="VendorName" ConvertEmptyStringToNull="false" Type="String" />

    <asp:Parameter Name="Status" ConvertEmptyStringToNull="false" Type="Char" />

    <asp:Parameter Name="AssetName" Type="String" />

    <asp:Parameter Name="Units" Type="Int32" />





    Thanx in advance[:)]

    Friday, December 22, 2006 6:36 AM

All replies

  • User288029314 posted

    Here is an example of a dropdown list from one of my sites that has it's selection values populated from 1 datasource but it's SelectValue is bound to another.

    <asp:DropDownList ID="ddlPCModel" runat="server" DataSourceID="sqldsPCLookup" DataTextField="Model"

    DataValueField="Model" SelectedValue='<%# Bind("PCModel") %>'>

    Friday, December 22, 2006 10:13 AM
  • User-694414214 posted

    I tried using the following code..

    <asp:DropDownList ID="DropDownList1" runat="server" Style="" Width="94px" DataSourceID="SqlDataSource3" DataTextField="VendorName" DataValueField="VendorName" SelectedValue='<%# Bind("VendorName") %>'/>

    still the same problem....

    I think this is hapenning due to the empty string values in the Vendorname column that has been bound to the dropdownlist1.....

    I need to replace these empty cells with the data selected from the dropdownlist...

    Do i need to write some code for gridview_Itemdatabound or gridview_ItemUpdating to tackle this issue....






    Saturday, December 23, 2006 12:49 AM
  • User1172451119 posted

    Hi, brazen: 

    This is quite a problem if you have not maintained data integrity, and/or if your Select statment in your dropdownlist data source does not include particular values.

    Plz have a look at this article and amend your datasource to have a valid datasets.


    Monday, December 25, 2006 2:48 AM
  • User-1153868280 posted

    I get this same error but the URL Link provided does not help with my scenerio. When I go to edit bindings form my user control The Binding for visible fields are "greyed out" including the two-way databinding.

    I have a form view edit item template. I have a user control that makes up two dropdownlists. The user control has two properties that return the slected value.

    Cany anyone provide some insight on how to do this through the source code?

    Thursday, January 4, 2007 11:21 AM
  • User1321126642 posted

    I too get this error - my data set IS valid and frustratingly it works sometimes (!)

    I have found redoing the dropdownlist on the page sometimes corrects the problem, as occasionally does refreshing the schema, but I am trying to complete a form with 6 of these on and it's like juggling plates - am I doing something wrong? why does it seem so flaky?

    Sorry to not offer insight just saying I've got the same problem...

    Thursday, January 11, 2007 7:27 AM
  • User1584810536 posted

    MS and many coders say this is the correct behaviour, to the rest of us normal people its just a stupid pain in the arse that we could do without.

     I add a null to the select command eg "select cola, colb from table1 union select null, null"

    Or you can populate the ddl via code, this is VB:

       Dim strCON As String, sqlCON As SqlConnection
            Dim strSQL As String, sqlCOM As SqlCommand, sqlDRD As SqlDataReader

            strCON = ConfigurationManager.ConnectionStrings("con_db_TM").ToString
            sqlCON = New SqlConnection(strCON)


            strSQL = "select distinct tr_code_sub from dbo.tbl_transactions " & _
                       "where tr_code = '" & Me.ddlCode.SelectedValue & "'"

            sqlCOM = New SqlCommand(strSQL, sqlCON)
            sqlDRD = sqlCOM.ExecuteReader


            With sqlDRD
                If .HasRows = True Then
                    While .Read
                    End While
                End If
            End With


    Thursday, January 11, 2007 8:34 AM
  • User-1153868280 posted

    It works "sometimes" because it can find the value both in the dropdownlist and the table your are binding your details view or form view to. 

    Let's say you have a dropdownlist with numbers 1 - 9. Then your form view or details view is bound to the data table so you can have the "selected value" displayed when you edit a record. When you view various records some have 1 - 9 in the data table and it can find the value in the dropdownlist and show it as the selected value. Lets say the next record has a 10 or a 0 or is Null, then it can't find a value to show as selected.

    I think MS assumes that all db have referential integrity. There are many legacy databases that are not perfect.

    So really there are two ways to get by this issue that I've found in the past few week. Either clean up your data in the database and fix all the relationship's or use a user control for the dropdownlist in your application. See this thread for more help with the user control. http://forums.asp.net/thread/1518715.aspx 

    Thursday, January 11, 2007 9:59 AM
  • User-432871419 posted

    Hi There

     I've recently come to asp.2 from 1.1 and am still finding my way. I'm getting the same problem 'dropdownlist has a selected value which is invalid' problem. I have basically added a yes and no text value with corresponding 1 and 0 values to the dropdown list. i've bound the value field to the datasource to reflect a binary column field. I'm sorry but i just do not see why this will not work as the value very clearly exists in the list. any ideas on this?

    Wednesday, April 18, 2007 4:49 AM
  • User288029314 posted
    Check to make sure that data table doesn't have blank or null values.  All records in the data table should have a 1 or a 0 in the column bound to the drop down.
    Wednesday, April 18, 2007 9:45 AM
  • User1452995550 posted

    Thanks DetroitJ

    Your first posts help me the most.  this one.

    >>Here is an example of a dropdown list from one of my sites that has it's selection values populated from 1 datasource but it's SelectValue is bound to another.

    see above...

    If you are new, some of the posts about this error are quite confusing.  I just created a new table in the database that my Dropdown could pull from.  a very simple table.

    two columns although only one column would have been enough for my situation. 

    like this

    id   Locationname

    1  Unassigned

    2  Location1

    3 Location2

    4 Location3

    Now like what DetroitJ said  the list is pulled from our new table but saves the data to the main table. The GenLoc (stands for General Location) is in the main table I am saving to. LocationName is from our new table.  

    <asp:DropDownList ID="DDGenLoc" runat="server" DataSourceID="SqlDS_GenlOcation" DataTextField="LocationName" DataValueField="LocationName" SelectedValue='<%# Bind("GenLoc") %>'>


    the SqlDS_GenlOcation data adapter just selects the items in this small table above

    but the selectedValue is bound to the table that does not have values in it yet. 

    Both DataTextField="LocationName" DataValueField="LocationName"  (so the first column is not necessary for me, because I am using a dataform.  I am already in the record.)

    Then I put this in the code behind

    Protected Sub FVWorkspace_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FVWorkspace.DataBound

    If Me.FVWorkspace.CurrentMode = FormViewMode.Edit Then

    Dim ddl As DropDownList = CType(Me.FVWorkspace.FindControl("DDGenLoc"), DropDownList)

    ddl.Items.Insert(0, New ListItem("Unassigned", "0"))

    End If

    End Sub

    Also in my main table I populated the entire GenLoc column with the string "Unassigned"  well only where the rows do not have values.

    This is the easiest way out of this mess.  If you can't beat it join it. put the data it wants in the tables.

    forget the if null then crap.  Its a pain. 











    Tuesday, May 1, 2007 5:59 PM
  • User1452995550 posted

    I take part of that back.

     You do not even need that code behind section.

    just delete

    Protected Sub FVWorkspace_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FVWorkspace.DataBound

    If Me.FVWorkspace.CurrentMode = FormViewMode.Edit Then


    Dim ddl As DropDownList = CType(Me.FVWorkspace.FindControl("DDGenLoc"), DropDownList)

    ddl.Items.Insert(0, New ListItem("Unassigned", "0"))

    End If

    Tuesday, May 1, 2007 6:05 PM
  • User663334535 posted


    I encountered the same problem today but I think there is another more elegant solution than updating all the tables. Having a null value in a column is a common requirement.
    All the list controls have a property called AppendDataBoundItems which is a boolean. If you set it to true than all the items that you add to the control before data binding will be preserved.
    So in our case I think we could do something like:

    <asp:DropDownList ID="Category" runat="server" AppendDataBoundItems="true">
                    <asp:ListItem Text="Please select" Value="" />
    After you databind the control you'll still have the Please select item.
    I didnt try it yet but I think this is the way to go around null values. I'll give it a try and let you know.
    Regarding broken foreign keys, you might want to write custom code to handle it.



    Thursday, June 21, 2007 1:04 PM
  • User1312078811 posted

    I solved this issue on my project by making my itemTemplate and EditItemTempates bound to different names

    <asp:TemplateField HeaderText="Room" SortExpression="Room">


    <asp:DropDownList ID="ddlRoom" runat="server"


    SelectedValue='<%# Bind("TRAINING_ROOM") %>'

    DataTextField="ROOM" DataValueField="ROW_ID"

    Font-Names="Verdana" Font-Size="X-Small" Width="175px"


    <asp:ListItem Value="">(--Select One--)</asp:ListItem>



    <ItemStyle Width="250px" />


    <asp:Label ID="lblRoomName" runat="server" Text='<%# Bind("ROOM_NAME") %>'></asp:Label>



    Wednesday, August 1, 2007 6:37 PM
  • User391255243 posted

    I fixed this issue by setting up my DropDownList like this:

    <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="ReferralDataSource"
    DataTextField="FieldValue" DataValueField="LookupId" Enabled="False" SelectedValue='<%# Bind("ReferralSource") %>'
    <asp:ListItem Value="0">Please Select</asp:ListItem>
    Then setting the default value in the database to 0, which sets the default selected item to "Please Select"


    Tuesday, April 15, 2008 6:25 AM
  • User1312078811 posted

     look over this code in detail to see the changes... Add the changes to your code and see if this works... it sound like you have vaules in your table that are Null or have no value, so in the dropdown list i added <asp:ListItem Value="">Select</asp:ListItem> . The word Select will be the default that shows at the top of the list with a value of Nothing. See the Value="". I hope this helps.

    <asp:DropDownList ID="DropDownList2" runat="server" Style="" Width="39px" selectedvalue='<%# Bind("Status") %>' AppendDataBoundItems="True">


    <asp:ListItem Value="">Select</asp:ListItem>

    <asp:ListItem Value="A"></asp:ListItem>

    <asp:ListItem Value="P"></asp:ListItem>

    <asp:ListItem Value="D"></asp:ListItem> 


    Wednesday, April 16, 2008 6:05 PM
  • User1312078811 posted
    also, pay attention to the AppendDataBoundItems="True" do not for get to add that to you code.
    Wednesday, April 16, 2008 6:07 PM
  • User1091077658 posted

    mhlove, Thanks for the suggestion, I did check that too--it's set

    Wednesday, April 16, 2008 6:11 PM
  • User1091077658 posted

    mhlove--thanks for the suggestion, unfortunately null or blank values are not my problem--this is still in design phase, I only have 5 recs in the database, trust me, no nulls or blanks in the field I'm using.  I think I'm going to tear it down and start again--amazingly that works a lot with .NET (from the same folks who brought you Shut Down--Reboot in Windows!  [:)]


    Wednesday, April 16, 2008 6:14 PM
  • User-2109426844 posted

    Personally I think the best solution is to check the items that are being bound to the DropDownList to ensure your value is in there.

    There is an article showing this method here:





    Saturday, August 23, 2008 9:56 PM
  • User1029898582 posted

    I Too have the same problem

    Is this a verfied bug in .NET?

    Im trying to follow that Tutorials both on here http://www.asp.net/learn/data-access/tutorial-20-cs.aspx and on msdn http://msdn.microsoft.com/en-us/library/bb426884.aspx

    None of them mentioning any workaround to get this to work

    But still as soon as i hit the "Edit" buton on my gridview i get the "'DDL2' has a SelectedValue which is invalid because it does not exist in the list of items.
    Parameter name: value"

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

    the data exists for sure and there is no null values


    Thursday, September 11, 2008 4:18 PM
  • User1091077658 posted

    Oprhan, one thing to check would be the size and type of fields in the table that has your drop down options and the table that is supposed to store the resulting selection--they have to be exactly the same or else you will get this message. 

    That's what caused my problem, one was 2 character, the other was 3--a typo on my part, they were both supposed to be 2.  Once I corrected this everything worked fine--it's an awful error message that .NET gives you because it makes you think you've got a bad field name or null data which is what everyone tells you to check (all well-meaning people to be sure, but when I explicitly stated I had no null or blank fields--I only had 5 recs in the DB, I could open it in SQL Server Manager and instantly verify there were no null fields--and everyone kept suggesting the same thing it was frustrating).

    Thursday, September 11, 2008 4:47 PM
  • User1029898582 posted

    thx for your answer acmassie

    Not sure if I understand you rightm but its just a integer value.

    Im picking up a ID from one table, trying to add it to the other table, as a realtion reference

    It "works" if I unchek the "Two-way Binding" but then ofcourse the field will have  null for value


    Friday, September 12, 2008 3:04 AM
  • User-731922569 posted

    Cheers cosmin.onea! AppendDataBoundItems was exaclty the kind of thing I was looking for!

    Friday, October 17, 2008 7:39 AM
  • User-207750841 posted

    Not sure if this is still needed, but ran into  the same issue, the code below fixed the problem.

    Note that the "DEFAULTVALUE", is a value that is known to exist in the table used to populate the

    drop-down. Could have statically populated the drop down, but then would have to manually update the code each time the

    available selection list changes.

    protected void OnDataBinding_ddlApptype(object sender, EventArgs e)


    DropDownList ddl = (DropDownList)sender;if (ddl != null)


    if (ddl.SelectedValue == null || ddl.SelectedValue == "")

    ddl.SelectedValue = "DEFAULTVALUE";



    Wednesday, October 29, 2008 3:30 PM
  • User1939422607 posted


      I faced the same problem, but i fixed this as below..

    One thing you have to observe: i.e binding column should not have null values. There should not any scope to save the blank field in that column..

    for example:

    this is dropdownlist in gridview

    <asp:DropDownList ID="DropDownList4" runat="server" Enabled =true
                            SelectedValue='<%# Bind("WORKTYPE") %>' AppendDataBoundItems =true>
                            <asp:ListItem Value="PR">Processing</asp:ListItem>
                            <asp:ListItem Value="QC">Quality Checking</asp:ListItem>
                            <asp:ListItem Value="Both">Both</asp:ListItem>


    the WorkType column is  CHAR(10)

    while saving PR in that WorkType column, it occupies only 2 bits of space, remaining 8 bits of space occupies null values/Spaces..

    so it is not matching with the dropdownlist PR value.. Because of that reason we got that error..

    More concentrate on this.. Remove the error and Happy Coding..

    Thanks and Regards



    Monday, November 3, 2008 2:08 AM
  • User-1939655422 posted

    I would like to try this.. Can you translate this to VB?



    Sunday, November 30, 2008 3:13 PM
  • User-1240533334 posted

    I wrestled with this one also and it had to do with null values in the db. The db column is of type 'int', so I made sure that there are no null values in the column, rather the default value is 0.  Also, I made sure that there was no value for 0 in the ref table that I was querying for the match.

     Now when the ddl loads, it defaults to "Please Select" if there is no recorded value.


      <asp:TemplateField HeaderText="Surgical Subspecialty" >
    <asp:dropdownlist ID="ddlSubElectives" SelectedValue='<%# Bind("surgicalsubspecialty") %>' DataTextField="elective_name" DataValueField="elective_id" Enabled="false" runat="server" AppendDataBoundItems="True" datasourceid="sdsSubElectives">
    <asp:ListItem Value="0">Please Select</asp:ListItem>
    <asp:dropdownlist ID="ddlSubElectivesEdit" SelectedValue='<%# Bind("surgicalsubspecialty") %>' DataTextField="elective_name" DataValueField="elective_id"
    runat="server" AppendDataBoundItems="True" datasourceid="sdsSubElectives">
    <asp:ListItem Value="0">Please Select</asp:ListItem>
    Wednesday, December 24, 2008 9:33 AM
  • User762178767 posted


    again, same problem as everyone here. Unfortunately none of the solutions from this thread seem to work in my scenario! Which is kind of a pain because I've been fighting with a simple gridview for a few days now! I have a dropdown in the gridview which selects someones name, and the value is their particular sequence which is found in the query where the data comes from. This "sequence" is then used with other data used in that row to insert into a table. This problem just wont go away.

    I have created a page that runs the same query to return ID (their sequence), name and code (like a login), and then on changing the ddl a label returns the value. It worked fine, as it should for example, Me (in the db) = 1193 and so on.

    I think i'm having some miss match between data trying to be stored and what the records actually holding (eg trying to store sequence into the wrong column or something) but nothing works and nothing appears to contain something that could cause such an error? This is extremely frustrating!

    Monday, April 20, 2009 9:41 AM
  • User-676323729 posted

    hey friends!!!


    Wednesday, May 13, 2009 4:54 AM
  • User-676323729 posted

    hey friends!!!


    is the
    Wednesday, May 13, 2009 4:54 AM
  • User-676323729 posted

    hey friends

    here are some gideliness for solving this problem.

    Check whether the Value field of the dropdown is same as the database.column name

    Check whether that columns contain null values in that column.

    Thank you

    Wednesday, May 13, 2009 4:54 AM
  • User-19491302 posted

    I too have the same problem, my code:

                        <asp:TemplateField HeaderText="Decide:" SortExpression="Decide">
                                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Decide") %>'></asp:Label>
                                <asp:DropDownList DataTextField="Decide" DataValueField="Decide" ID="DropDownList2" Runat="server" SelectedValue='<%# Bind("Decide") %>' AppendDataBoundItems="true" >
                                   <asp:ListItem Value="Accept">Accept Job</asp:ListItem>
                                   <asp:ListItem Value="Reject">Reject Job</asp:ListItem>
                                <asp:TextBox ID="TextBoxDecide" runat="server" Text='<%# Bind("Decide") %>'></asp:TextBox>

    Now if I change the EditItemTemplate to <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Decide") %>'></asp:TextBox> it works fine......WTF

    I have also another Template that uses the same idea, and it works fine!

    All the rows in the DBASE have records in it, so can anyone give me a heads up on why this isn't working?

    Monday, May 18, 2009 10:27 AM
  • User-1939655422 posted

    Have you tried adding a default value in the field in the table of your database?

    Monday, May 18, 2009 2:05 PM
  • User-19491302 posted

     Yeah I put in 'Awaiting' as a default value. But still the same error?

    Tuesday, May 19, 2009 5:28 AM
  • User-19491302 posted

    I have tried this on another DetailsView as well, and it's pulling the same error.
    I can't understand it at all [scratchHead]

    Tuesday, May 19, 2009 7:21 AM
  • User-19491302 posted

    I have also altered the Dbase column to a bit 1 or 0, and set the default value to 0. Taken the Not Null option off as well, but it is STILL returning the same error.

    I have even changed it to char(9) and put the default value as Awaiting, still no luck.

    Thought I would try radio buttons instead, and it still pulls the same error, what's going on?

    Wednesday, May 20, 2009 5:29 AM
  • User-923888396 posted

    Just to follow up on a previous suggestion I ran into a similar problem getting this error message. I did have to go back to my SQL Server 2008 table and modify columns that corresponded to the dropdownlist items.  I think perhaps the slightest difference such as column length or format such as char or nchar could cause problems. Also using dropdownlists to insert we often require some sort of default option on a pre-select.  When it comes to edits in a GridView I think we only want to pre-select existing values.  When copying code from forms and placing it in the GridView Template we must think about what is happening and make our adjdustments such as not including a detault value that has no real value in a column of our target table.  It is possible that on an insert when a listitem on a dropdownlist is left untouched hence sent as a default value that code behind overrides and selects a valid value before the SQL insert is done.  Could end up being a little tricky. 

    Wednesday, June 24, 2009 2:10 PM
  • User-1251604557 posted

    the first post was in 2004

    the last one was in 2009

    I'm facing the same porblem and until now there is no official solution from MS ?! 

    Wednesday, July 1, 2009 10:43 AM
  • User9812958 posted

    Hi all!

    Here's a forgiving DropDownList allowing you to bind to invalid values. Hope it can help someone. :)



    Monday, July 6, 2009 7:15 AM
  • User-1074610410 posted

    In my case I had a field on the SQL table populating the dropdownlist set to nvarchar(10) and had omitted to notice that the relevant field on the main data table was char(10).....doh! This meant, of course, that extra spaces were being added to the data thus rendering the 'selectedvalue' to be non existant. Fixed.

    Thursday, July 16, 2009 10:21 AM
  • User908914832 posted

    Hey guys, this issue has been plaguing me too. In my code, I have a Gridview populated by a database which will have null values in it. The user then has to edit the data in the database until all cells for a row is filled and then, if the data is good, the user can accept the record into a primary database (which does not allow null values). Optionally, if the data is bad, the user can reject the record and it will be processed again. In order to make things easier for the user, several of the cells will become drop down lists when the edit button is pressed. I've had trouble getting my update to recognise the value of a DDL so I followed the guide at http://msdn.microsoft.com/en-gb/library/ms972948.aspx in the hopes that I'll get it right this time.

    I've only created one DDL for the time being (may as well get one working before I start on all the others) and it will only have the values "Up" or "Down". These are hard coded. Whenever I hit the "edit" button, I get the error:

    "'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.

    Parameter name: value"

    I've tried all the methods here and I can't get anything to work. My code for the particular template field is as follows:

    <asp:TemplateField HeaderText="Direction" SortExpression="Direction">
            <asp:DropDownList ID="DropDownList1" runat="server"
            SelectedValue='<%# Bind("Direction") %>' AppendDataBoundItems="True">
                <asp:ListItem Value="0" Selected="True">Up</asp:ListItem>
                <asp:ListItem Value="1">Down</asp:ListItem>
            <asp:Label ID="Label4" runat="server" Text='<%# Bind("Direction") %>'></asp:Label>
        <ControlStyle BorderColor="#350B59" Width="55px" />
        <FooterStyle BorderColor="#350B59" Width="55px" />
        <HeaderStyle BorderColor="#350B59" Width="55px" />
        <ItemStyle BorderColor="#350B59" Width="55px" />

    Anyone got any ideas? I'm getting desperate!

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

    Edit: Almost forgot, if it helps, the data type for the column is 'nvarchar(4)' and nulls are allowed.


    I read something that suggested that if I add a ListItem at the top of the list like below the error would be solved:

    '<asp:ListItem Value="" Selected="True"></asp:ListItem>'

    And it did! However, as you will all notice (and as I foolishly didn't notice), when I updated, the value of the cell would become 0 or 1 but I want the value to be Up or Down. Changing Value="0" to Value="Up" and 1 to Down yielded the same error as I have been receiving all this time.

    Tuesday, July 28, 2009 7:50 AM
  • User-923888396 posted

    Did you get your problem resolved? 

    If you are extracting data from a database that maps to values in your DDL then your item list must have a value for each existing value that is extracted.  Are you pre-selecting a value in the list based on the value you read in the database? I don't know of a way to handle a null value in the list.  If you have nulls in the values you are extracting how would they map to a value in your list?  Is zero a different value in the database than null? If you want to say that '0' (zero) is that same as null you might have to convert nulls to zero prior to an edit that tries to pre-select a value of null which will fail.

    Any other values in the database that you feel might get read that don't have a value in your item list?

    The auto edit in the Gridview will try and pre-select for you based on your bind value.

    If you have Visual Studio set a break point at your SQL reader or wherever you are getting data from the database. Then look at the value of the data item in your bind and note whether you are getting a value not in your list item values.







    Tuesday, July 28, 2009 11:57 PM
  • User908914832 posted

    The DDL is hard coded with values as I only need Up and Down in one list and the months of the year in another. There are no null values in the DDL.

    I think that because the DDL is hard coded, the methods to fix this error in this forum aren't working for me.

    Wednesday, July 29, 2009 5:39 AM
  • User-923888396 posted

    By DDL I'm assuming you mean the Drop Down List.  The 'Up' and 'Down' are text strings to be displayed in the drop down list.  You have values in of '0' and '1' in the Drop Down List.  In your datasource you have nulls, '0' and '1' in a Direction column of a table of some sort which is what you are binding to. The values in ASP.LISTITEM identified by value='0' etc... is what you are matching on. Try testing with only Direction values of '0' and '1' in your datasource (not the DDL list items) and see if you get a clean run.  

    Wednesday, July 29, 2009 10:17 AM
  • User-1251604557 posted

     Still no solution..

    I think there is no doubt that the problem is in the data type of the table field because for example when I make the datatype "text" in ACCESS database I get the error but when I change it to "integer" the problem disappears, but why it works for some "Text" columns and not for other columns?

    Thursday, August 6, 2009 1:42 AM
  • User-923888396 posted

    Who can say really with these tools. It's open system technology. The same problems in .NET and Java. A lot of time spent type casting and converting values depending on the control or datasource interface.  Too much to even try to reason out.  I stopped trying to make sense out of everything in .NET months ago. When things get really layered and problems occur I often peel back the code and get things real simple. Then it is the old fashioned method of looping through adding back code and waiting for the problem code to rear its ugly head.  I also learned to give up on trying to pound a solution into submission.  If it is too hard I find another way. Like water around a rock.



    Thursday, August 6, 2009 2:11 AM
  • User-1251604557 posted

    I hope this will be the final solution, if somebody has a small project and this solution didn't work with him I hope that he send me his small project so I make sure that he didn't miss any point.

     There are two columns involved:

    - The one that you retrieve the values from. Let’s call it "Status".

    - The one that you insert values to. Let’s call it "process_type".

     Suppose you have 3 values in the first column "Status": [New,In progress,Canceled]. In the GridVew or any data control you are showing the second column "process_type", and you want it to be shown as a DropDownList when you click "Edit", then you have to

    open the second column "process_type" from the database and make sure that there is no cell has a value which does not exist in the first column "Status", even Null are not accepted in the second column unless you have null values in the first column.

     There is one small thing left you might not notice if you have added a WHERE clause, when you make your SELECT statement for the second column "process_type", and you have added a WHERE clause, you have to make sure that all the values that will be retrieved from this SELECT statements match all the values that will be retrieved from the first column "Status".

     Advice: I think it's obvious now that you have to make the right user interface in such a way to force the user to enter the values that match with the vales from the first column. usually you will be using a dropdownlist.

    Sunday, August 9, 2009 1:07 AM
  • User-1298645164 posted

    Please make sure that Datasource has the value you are trying to assign back.

    Error happens when control can not find the assigned selected value in the orginal (DataSource) collection.

    Tuesday, August 11, 2009 7:12 PM
  • User-976605955 posted


    I solved this issue adding the following to my  DropDownList ListItems:


    And it worked!

    I hope it helps. Cool



    Friday, November 20, 2009 3:36 PM
  • User-2109426844 posted

    My preferred solution to this problem is to remove the SelectedValue property for your dropdownlist to remove your binding and then add some code which will search through the data items bound to your dropdownlist, and if your item isn't found then display the "Please Select" option.

    More details here

    Sunday, December 6, 2009 4:52 PM
  • User-313012104 posted

    I just made a custom drop downlist class, that essentially treats the SelectedValue property as TrySelectedValue, and added options to control how to handle the missing value.

        [ParseChildren(true), PersistChildren(false)]
        [ToolboxData("<{0}:CustomDropDownList runat=server></{0}:CustomDropDownList>")]
        public class CustomDropDownList : DropDownList
            private string cachedSelectedValue = null;
            private bool performedDataBinding = false;
            private bool valueIsMissing = false;
            #region Options
            private ListControlOptions _options = new ListControlOptions();
            /// <summary></summary>
            public ListControlOptions Options
                    return _options; 
                    _options = value; 
            #region SelectedValue
            public override string SelectedValue
                    return base.SelectedValue;
                    // Prevents error: 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
                    if (performedDataBinding && !valueIsMissing) base.SelectedValue = value;
                    else cachedSelectedValue = value;
            #region PerformDataBinding
            protected override void PerformDataBinding(IEnumerable dataSource)
                performedDataBinding = true;
            #region Select
            private void Select()
                int indexOf = -1;
                ListItem item;
                if (cachedSelectedValue != null)
                    item = Items.FindByValue(cachedSelectedValue);
                    indexOf = Items.IndexOf(item);
                // Always insert the "(None)" if AllowNull is true
                if (Options.AllowNull)
                    ListItem nullItem = new ListItem(Options.NullText, string.Empty);
                    Items.Insert(0, nullItem);
                valueIsMissing = (indexOf == -1);
                // Perform selection
                if (indexOf != -1 && cachedSelectedValue != null)
                    base.SelectedValue = cachedSelectedValue; // Normal case, value was found. 
                else if (cachedSelectedValue == null && Options.AllowNull)
                    base.SelectedValue = string.Empty; // Select null when AllowNull is true.
                else if (indexOf == -1 && cachedSelectedValue != null && !Options.AllowNull)
                    // Missing selected value
                    if (Options.MissingMode == ListControlMissingMode.None)
                        // Do nothing, leave SelectedIndex at 0
                    else if (Options.MissingMode == ListControlMissingMode.ThrowException)
                        string format = "'{0}' has a SelectedValue which is invalid because it does not exist in the list of items.";
                        string message = string.Format(format, ID);
                        throw new ArgumentOutOfRangeException(message);
                        // Insert missing placeholder
                        string itemText = string.Empty;
                        if (Options.MissingMode == ListControlMissingMode.InsertSelectedValue) itemText = cachedSelectedValue;
                        else if (Options.MissingMode == ListControlMissingMode.InsertPlaceholder) itemText = Options.MissingText;
                        else if (Options.MissingMode == ListControlMissingMode.InsertPlaceholderFormatted) itemText = string.Format(Options.MissingFormat, cachedSelectedValue);
                        ListItem missingItem = new ListItem(itemText, string.Empty);
                        Items.Insert(0, missingItem);
                        base.SelectedValue = string.Empty;

        /// <summary>Determines what to show when the selected value cannot be found in the ListControl when being data bound.</summary>
        public enum ListControlMissingMode
            /// <summary>1. No placeholder is inserted to indicate the selected value.</summary>
            None = 1,
            /// <summary>2. Insert the selected value that is missing.</summary>
            InsertSelectedValue = 2,
            /// <summary>3. Insert a placeholder for the missing item. Example: "(Select)".</summary>
            InsertPlaceholder = 3,
            /// <summary>4. Insert a placeholder for the missing item using string.Format syntax. {0} is the selected value. Example: "(Not Found) Wisconsin"</summary>
            InsertPlaceholderFormatted = 4,
            /// <summary>Throws an exception. Default ListControl behavior.</summary>
            ThrowException = 5,
        public class ListControlOptions
            private const string selectParenthesis = "(Select)";
            private const string notFoundParenthesisFormat = "{0} (Not Found)";
            private const string noneParenthesis = "(None)";
            #region AllowNull
            private bool _allowNull;
            /// <summary>True if a selected value is not required.</summary>
            public bool AllowNull
                get { return _allowNull; }
                set { _allowNull = value; }
            #region NullText
            private string _nullText = noneParenthesis;
            /// <summary>The text to display in the top list item to indicate a null value.</summary>
            public string NullText
                get { return _nullText; }
                set { _nullText = value; }
            #region MissingText
            private string _missingText = selectParenthesis;
            /// <summary></summary>
            public string MissingText
                get { return _missingText; }
                set { _missingText = value; }
            #region MissingFormat
            private string _missingFormat = notFoundParenthesisFormat;
            /// <summary></summary>
            public string MissingFormat
                get { return _missingFormat; }
                set { _missingFormat = value; }
            #region MissingMode
            private ListControlMissingMode _missingMode = ListControlMissingMode.InsertPlaceholder;
            /// <summary></summary>
            public ListControlMissingMode MissingMode
                get { return _missingMode; }
                set { _missingMode = value; }

    Thursday, December 31, 2009 12:10 PM
  • User-2118233109 posted

    I too had an invalid SelectedValue.

    I had an edit template field where I put a drop down list in it.  I was trying to populate the drop down list with the two distinct values of the field 'Status'.

    My problem was in the SQL datasource.  Through the wizard, I accidentally made my query "SELECT DISTINCT [Status] FROM [tbl1I1601LookupBackup_01142010] WHERE ([Status] = @Status)".

    The WHERE clause was referring back to my drop down list.

    By changing the query to this "SELECT DISTINCT [Status] FROM [tbl1I1601LookupBackup_01142010]", I fixed the problem.

    Wednesday, February 3, 2010 6:03 PM