[英]ASP.Net: Getting DataKey from GridView on Edit and Delete
我正在使用GridView
控件,該控件被數據綁定到從實用程序方法返回的對象List
。 GridView
控件將其中一列設置為其DataKey。 當一行被Selected
,它會觸發Selected事件處理程序,我可以使用myGridView.SelectedDataKey.Value
來獲取所選行的DataKey列的值。
但是,當行被Edited
或Deleted
時的事件處理程序似乎沒有一種機制來獲取相關行的DataKey值。 這些事件處理程序的事件arg參數包含GridView
中行的索引,但我特別在DataKey值之后。
通過實用程序方法重新獲取對象列表以及從事件arg參數獲取的索引不是一個選項,因為對象列表可能已更改。
誰能告訴我怎么做到這一點?
TIA
protected void gridQuestion_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = (int)grdQuestions.DataKeys[e.RowIndex].Value;
}
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);
}
}
這是我的解決方案:
在gridview中設置DataKeyNames =“id”。 這樣行就會有一個datakey
然后在Grd_RowDataBound中為按鈕添加一個屬性,如下所示:
LinkButton Btn= (LinkButton)e.Row.FindControl("BtnDelete");
if (Btn!= null)
{
Btn.Attributes.Add("ROW_INDEX", e.Row.RowIndex.ToString());
}
然后在OnClick事件中使用:
int rowIndex= Convert.ToInt32(((LinkButton)sender).Attributes["ROW_INDEX"].ToString());
int id= Convert.ToInt32(Grd.DataKeys[rowIndex].Value);
並且您在gridview的回發中獲得了datakey值。
您可以使用從編輯/刪除事件返回的索引號,然后手動選擇該行
String yourDataKey = GridView.DataKeys[e.NewSelectedIndex].Item["youfield"].tostring();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.