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

时间:2015-01-31 08:28:46

标签: c# asp.net gridview

我在尝试保存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>

代码背后

//保存TestDetails

   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();

            }
    }

1 个答案:

答案 0 :(得分:1)

您应该使用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);
相关问题