I am getting an error on accessing gridview hidden field Ids while trying to save the gridview row details. What i want to do is to save the all gridview rows back to database. I am bit confused on accessing the value of the row ids. 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
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
:
// 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.