Search code examples
asp.netvb.netdata-bindingdetailsview

Binding DropDownList to Detailsview without Data Source


Im trying to do bind a dropdown list to a details view but keep getting an error about the dropdown list ID field:

<asp:TemplateField HeaderText="Approval">
                <ItemTemplate>
                    <asp:DropDownList ID="Approved" runat="server" DataValueField="Approved" SelectedValue='<%#Bind("Approved") %>'>
                        <asp:ListItem Text="Approved" Value="Approved" />
                        <asp:ListItem Text="Denied" Value="Denied"/>

                    </asp:DropDownList>
                </ItemTemplate>                   
 </asp:TemplateField>

The error message as follows:

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

What is the proper way to attach the value of the dropdownlist to my object so that it can be properly created in the database? Most of my searches keep telling me how to bind a dropdownlist to an object data source, but that is not what I need to do. This is a basic drop down list of 2 items that will never change.


Solution

  • This error happens because you are binding the SelectedValue of the DropDownList to the "Approved" field of your DetailsView's datasource, but the value it's trying to assign isn't one of the two you have listed ("Approved" and "Denied").

    I see you have set DataValueField="Approved". Are you setting the Dropdown's Datasource in code-behind? Because that is not going to set your ListItems to the values from the "Approved" column in the DetailsView's datasource, it's setting them to whatever the datasource for the Dropdown is.

    Depending on your logic, here are some possibilites:

    • Make sure your static items match the possible items returned in the "Approved" field of the DetailsView. Or,
    • Bind the DropDownList to a dataset that includes all the possible values from "Approved", and completely removed your static items. Or,
    • Set AppendDataBoundItems="True" in your DropDown and have both static and databound items