[英]How to get values of the gridview hidden fields in asp.net
I am getting an error on accessing gridview hidden field Ids while trying to save the gridview row details. 我在尝试保存gridview行详细信息时访问gridview隐藏字段ID时遇到错误。 What i want to do is to save the all gridview rows back to database.
我想要做的是将所有gridview行保存回数据库。 I am bit confused on accessing the value of the row ids.
我对访问行ID的值感到困惑。 Please help me to overcome this problem.
请帮助我克服这个问题。
<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>
//Save TestDetails //保存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();
}
}
You should use the DataKeys
: 您应该使用
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.