GridView:在GridView中编辑底层数据

时间:2012-01-12 01:34:53

标签: asp.net gridview

好吧,我有一个带有DropDownList的可编辑字段的GridView,如'TemplateField'。 我的代码:

<Columns>
    ...
    <asp:TemplateField SortExpression="Room" HeaderText="Room">
        <EditItemTemplate>
            <asp:DropDownList ID="DropDownList1" Runat="server" DataSourceID="categoryDataSource" DataTextField="RoomNumber" DataValueField="RoomNumber" SelectedValue='<%# Bind("Room") %>'>
            </asp:DropDownList>
        </EditItemTemplate>
    </asp:TemplateField>
    <ItemTemplate>
        <asp:Label Runat="server" Text='<%# Bind("Room") %>' ID="Label1"></asp:Label>
    </ItemTemplate>
</Columns>

我的数据库有表空间,其中有行:RoomId,RoomNumber。 在我的DropDownList中,我尝试设置表Rooms中的所有值。 表有3行(RoomId,RoomNumber):1 - 20; 2 - 12; 3 - 24.

但写下跟随错误:

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

参数名称:值 也许有人知道我在哪里错了吗?

编辑:这是SQLDataSource代码

<asp:SqlDataSource ID="categoryDataSource" Runat="server" 
    SelectCommand="SELECT [RoomId], [RoomNumber] FROM [Rooms] ORDER BY [RoomNumber]" 
    ConnectionString="Data Source=.\MSSQLSERVERR2;AttachDbFilename=|DataDirectory|\ARMDB.MDF;Integrated Security=True;User Instance=True">
</asp:SqlDataSource>

1 个答案:

答案 0 :(得分:3)

该错误表示您尝试在下拉列表中选择的值不存在。我认为这种情况的发生主要是因为没有在下拉列表中选择错误的字段值或设置错误的值。

例如,在您的情况下,很可能是您在引用的表中存储RoomId(而不是RoomNumber),因此您需要相应地绑定下拉列表的值字段

<asp:DropDownList ID="DDL1" Runat="server" DataSourceID="categoryDataSource" 
   DataTextField="RoomNumber" DataValueField="RoomId" 
   SelectedValue='<%# Bind("Room") %>'>

注意 DataValueField 值 - 其RoomId而不是房间号。 (假设Bind("Room")将返回房间ID)

相关问题