2

我有一个网格视图,它是从允许编辑的 sql 表中填充的。对于其中一个字段,我有它,因此用户必须从 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>

如果您为该字段已在表中存储值的记录选择“编辑”,则没有问题。但是,如果您选择“编辑”并且表中还没有相应的值,则会出现以下错误

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

在这种情况下,我如何解释空白或空值并使其工作?

4

2 回答 2

1

听起来您正在尝试更新不存在的记录。因此,您有几个选择,具体取决于您想要做什么。您可以捕获错误并向用户显示他们需要在编辑之前创建新记录的用户友好警报。或者,如果出现错误,您可以捕获错误并运行插入命令。或者你可以防止错误一起触发。这将是我的建议。在后面的代码中,当 dropdowlist 事件触发时,获取 ID 并运行查询以查看记录是否存在。如果是,请更新它。如果没有,要么提醒用户,要么你可以直接插入。如果您对如何执行此操作有具体问题,请告诉我。

于 2013-05-21T14:54:56.330 回答
1

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>
于 2013-05-21T15:00:02.890 回答