Grabbing Data from a GridView on PostBack

Have you ever wanted to grab bulk data on a grid view? It's actually not that hard at all. Set the System.Web.UI.WebControls.GridView.DataKeys Property on the Grid, then on the postback event iterate over the grid like so.

   1:  foreach (GridViewRow row in gridView.Rows) 
   2:  { 
   3:      DataKey data = gridView.DataKeys[row.RowIndex]; 
   4:      int Id = (int)data.Values["Id"]; 
   5:      TextBox myControl = row.FindControl("mycontrol") as TextBox; 
   6:      //do something with the data
   7:  } 

And on your GridView add the DataKeys Property

   1:  <asp:GridView ID="myGrid" runat="server" 
   2:       DataSourceID="myDataSource"
   3:       DataKeyNames="Id" >

No Comments