2011-10-18 50 views
4

我正在使用一個GridView控件,該控件是數據綁定到從實用工具方法返回的對象的ListGridView控件將其中一列設置爲其DataKey。當一行是Selected時,它會觸發Selected事件處理程序,我可以使用myGridView.SelectedDataKey.Value來獲取所選行的DataKey列的值。ASP.Net:從編輯和刪除從GridView獲取DataKey

但是,當行爲EditedDeleted的事件處理程序似乎沒有獲取有關行的DataKey值的機制。這些事件處理程序的事件arg參數包含GridView中行的索引,但我特別是在DataKey值之後。

通過實用程序方法重新獲取對象列表以及從事件arg參數獲取的索引不是一種選項,因爲對象列表可能已更改。

誰能告訴我怎麼做到這一點?

TIA

回答

16
protected void gridQuestion_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
    int id = (int)grdQuestions.DataKeys[e.RowIndex].Value;  
} 
+0

非常優雅。很好,不要按索引指向一個單元格。 –

0

你可以使用從編輯/刪除事件返回的索引號,然後選擇該行manualy

String yourDataKey = GridView.DataKeys[e.NewSelectedIndex].Item["youfield"].tostring(); 
2
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); 
    } 
} 
1

這裏是我的解決方案:

在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); 

,你得到了dataview的gridview回傳中的值。

+0

當然這個解決方案是爲未來askers – Bergkamp