Question

I have a situation where I have a gridview which is populated from a sql table which editing is allowed. For one of the fields, I have it so the user has to select a value from a drop down box in the edit template for the gridview.

<asp:TemplateField HeaderText="Department" SortExpression="Department">
                 <EditItemTemplate>
                     <asp:DropDownList ID="ddlEditDepartment" runat="server" 
                         SelectedValue='<%# Bind("Department") %>'>
                    <asp:ListItem>Department 1</asp:ListItem>
                    <asp:ListItem>Department 2</asp:ListItem>
                    <asp:ListItem>Department 3</asp:ListItem>
                     </asp:DropDownList>
                 </EditItemTemplate>
                 <ItemTemplate>
                     <asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
                 </ItemTemplate>
            </asp:TemplateField>

If you select "edit" for a record in which this field already has a value stored in the table for it, no problem. However, if you select "edit" and there is no value in the table for it yet, you get the following error

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

How can I account for blank or null values in this situation and make this work?

Was it helpful?

Solution

You're binding your DropDownList to a field named "Department" in your GridView's datasource:

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

It's kind of a hack, but you could modify the query that populates the Department field of your GridView to account for the nulls (by coalescing them out):

SELECT COALESCE(Department, "No department entered") AS Department
FROM YourTable

And then just add that as kind of a "default" option in your dropdown:

<asp:ListItem>No department entered</asp:ListItem>

OTHER TIPS

It sounds like you are trying to update a record that does not exist. So, you have a few options, depending on what you want to do. You could capture the error and display a user friendly alert to the user that they need to create a new record before editing. Or, you could capture the error and run an insert command if the error gets raised. Or you could prevent the error from firing all together. This would be my suggestion. In your code behind, when the dropdowlist event fires, take the ID and run a query to see if the record exists. If it does, update it. If not, either alert the user or you could just do the insert then. If you have a specific question on how to do this, let me know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top