ASP.Net: getting DataKey from GridView while editing and deleting

I am using a GridView control that is bound to List objects returned from a utility method. The GridView control has one of the columns defined as a DataKey. When the row is Selected , it fires the handler of the selected event, and I can use myGridView.SelectedDataKey.Value to get the value of the DataKey column for the selected row.

However, the event handler when the Edited or Deleted line does not seem to have a mechanism to get the DataKey value for the line in question. The arg event parameter for these event handlers contains the row index in the GridView , but I specifically after the DataKey value.

Retrieving the list of objects using the utility method together with the index obtained from the arg parameter of the event argument is not an option, since the list of objects can be changed.

Can someone tell me how can I do this?

TIA

+4
source share
4 answers
  protected void gridQuestion_RowDeleting(object sender, GridViewDeleteEventArgs e) { int id = (int)grdQuestions.DataKeys[e.RowIndex].Value; } 
+17
source
 protected void btnDelete_Click(object sender, EventArgs e) { try { int i; Con.Open(); cmd = new SqlCommand("USP_REGISTER", Con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@P_CH_ACTION_CODE", "D"); for ( i = 0; i <= grdApplication.Rows.Count - 1; i++) { CheckBox Ck=grdApplication.Rows[i].FindControl("cbItem") as CheckBox; if (Ck.Checked==true) { int Id = (int)grdApplication.DataKeys[i].Values["INT_ID"]; cmd.Parameters.AddWithValue("@P_INT_ID", Id); SqlParameter StrOut = new SqlParameter(); StrOut = cmd.Parameters.AddWithValue("@P_MSG_OUT", "out"); StrOut.Direction = System.Data.ParameterDirection.Output; cmd.ExecuteNonQuery(); StrRetVal = (string)cmd.Parameters["@P_MSG_OUT"].Value; } Con.Close(); } } catch (Exception ex) { Response.Write(ex.Message); } } 
+2
source

here is my solution:

in gridview set DataKeyNames = "id". this way the string will have datakey

then in Grd_RowDataBound add an attribute to a button like this one:

 LinkButton Btn= (LinkButton)e.Row.FindControl("BtnDelete"); if (Btn!= null) { Btn.Attributes.Add("ROW_INDEX", e.Row.RowIndex.ToString()); } 

then in the OnClick event use this:

 int rowIndex= Convert.ToInt32(((LinkButton)sender).Attributes["ROW_INDEX"].ToString()); int id= Convert.ToInt32(Grd.DataKeys[rowIndex].Value); 

and you got the datakey value in postbacks gridview.

+1
source

You can use the index number returned from the Edit / Delete event, and then select the row manually

 String yourDataKey = GridView.DataKeys[e.NewSelectedIndex].Item["youfield"].tostring(); 
0
source

All Articles