如何获取 asp.net 中 gridview 隐藏字段的值

How to get values of the gridview hidden fields in asp.net

我在尝试保存 gridview 行详细信息时访问 gridview 隐藏字段 ID 时出错。我想要做的是将所有 gridview 行保存回数据库。我对访问行 ID 的值有点困惑。请帮我解决这个问题。

       <asp:GridView ID="GridView1" runat="server"
                        DataKeyNames="ServiceID" Font-Names="Segoe UI Symbol" Font-Size="11pt" RowStyle-BackColor="#A1DCF2"
                        ShowFooter="true" Width="670px">
                        ForeColor="White" />
                        <PagerStyle CssClass="cssPager" />
                        <AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <%--ServiceID--%>
                            <asp:TemplateField HeaderText="ServiceID" ItemStyle-Width="100px">
                                <ItemTemplate>
                                    <asp:Label ID="lblServiceID" runat="server" Text='<%# Eval("ServiceId")%>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                            </asp:TemplateField>

                            <%-- ServiceName --%>
                            <asp:TemplateField HeaderText="Service" ItemStyle-Width="200px">
                                <ItemTemplate>
                                    <asp:Label ID="lblService" runat="server" Text='<%# Eval("ServiceName")%>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle Width="300px" />
                            </asp:TemplateField>
                         </Columns>
          </asp:GridView>

代码隐藏

//保存测试详情

   foreach (GridViewRow rw in GridView1.Rows)
    {
            var n = new TestDetail
            {
                PriceListId = txtPriceList.text,
                ServiceId = Convert.ToInt32(GridView1.DataKeys[rw.RowIndex].Value),
                Price = Convert.ToDecimal(txtPrice.Text.ToString()),
            };

            using (var context = new DiagEntities())
            {
                context.TestDetail.Add(n);
                context.SaveChanges();

            }
    }

你应该使用 DataKeys:

// Get the index of the current row.
int index = rw.RowIndex;

// Based on the index of the row 
// get the DataKey value and convert it to an int
ServiceId = Convert.ToInt32(GridView1.DataKeys[index].Value);