Reputation: 2905
I am using a GridView
control which is databound to a List
of objects returned from a utility method. The GridView
control has one of the columns set as its DataKey. When a row is Selected
, it fires the Selected event handler and I can use myGridView.SelectedDataKey.Value
to get the value of the DataKey column for the selected row.
However, the event handler for when a row is Edited
or Deleted
does not seem to have a mechanism to get the DataKey value for the row in question. The event arg parameter for these event handlers contains the index of the row in the GridView
but I'm specifically after the DataKey value.
Re-obtaining the List of objects via the utility method along with the index obtained from the event arg parameter is not an option because the List of objects may have changed.
Can anyone tell me how I can do this?
TIA
Upvotes: 5
Views: 53269
Reputation: 231
protected void gridQuestion_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = (int)grdQuestions.DataKeys[e.RowIndex].Value;
}
Upvotes: 17
Reputation: 599
here's my solution:
in the gridview set the DataKeyNames="id". this way the row will have a datakey
then in Grd_RowDataBound add an attribute to the button like this:
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 the gridview's postbacks.
Upvotes: 1
Reputation: 21
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);
}
}
Upvotes: 2
Reputation: 2443
You could use the index number returned from the Edit/Delete event and then select the row manualy
String yourDataKey = GridView.DataKeys[e.NewSelectedIndex].Item["youfield"].tostring();
Upvotes: 0