【问题标题】:How to get values of the gridview hidden fields in asp.net如何在asp.net中获取gridview隐藏字段的值
【发布时间】:2015-01-31 08:28:45
【问题描述】:

在尝试保存 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();

            }
    }

【问题讨论】:

  • 谢谢...现在它工作正常...上面给出了更正的代码。

标签: c# asp.net gridview


【解决方案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);

【讨论】:

  • 感谢克里斯托斯!我现在实现了相同的方法,它插入了比预期更多的行。
  • @你欢迎老兄。您将选择要插入的行。但是,正如我可以从您的代码中推断的那样,当您单击保存详细信息时,您会遍历 gridview 的所有行。因此,gridview 的所有行都将被插入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多