title: How to get values of the gridview hidden fields in asp.net
body: <p>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.</p>
  
  <pre><code>       &lt;asp:GridView ID="GridView1" runat="server"
                          DataKeyNames="ServiceID" Font-Names="Segoe UI Symbol" Font-Size="11pt" RowStyle-BackColor="#A1DCF2"
                          ShowFooter="true" Width="670px"&gt;
                          ForeColor="White" /&gt;
                          &lt;PagerStyle CssClass="cssPager" /&gt;
                          &lt;AlternatingRowStyle BackColor="White" /&gt;
                          &lt;Columns&gt;
                              &lt;%--ServiceID--%&gt;
                              &lt;asp:TemplateField HeaderText="ServiceID" ItemStyle-Width="100px"&gt;
                                  &lt;ItemTemplate&gt;
                                      &lt;asp:Label ID="lblServiceID" runat="server" Text='&lt;%# Eval("ServiceId")%&gt;'&gt;&lt;/asp:Label&gt;
                                  &lt;/ItemTemplate&gt;
                                  &lt;ItemStyle Width="100px" /&gt;
                              &lt;/asp:TemplateField&gt;
  
                              &lt;%-- ServiceName --%&gt;
                              &lt;asp:TemplateField HeaderText="Service" ItemStyle-Width="200px"&gt;
                                  &lt;ItemTemplate&gt;
                                      &lt;asp:Label ID="lblService" runat="server" Text='&lt;%# Eval("ServiceName")%&gt;'&gt;&lt;/asp:Label&gt;
                                  &lt;/ItemTemplate&gt;
                                  &lt;ItemStyle Width="300px" /&gt;
                              &lt;/asp:TemplateField&gt;
                           &lt;/Columns&gt;
            &lt;/asp:GridView&gt;
  </code></pre>
  
  <h2>Code Behind</h2>
  
  <p>//Save TestDetails</p>
  
  <pre><code>   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();
  
              }
      }
  </code></pre>