ASP.Net:在编辑和删除时从GridView获取DataKey

时间:2011-10-18 13:37:10

标签: c# asp.net gridview

我正在使用GridView控件,该控件数据绑定到从实用程序方法返回的List个对象。 GridView控件将其中一列设置为其DataKey。当行为Selected时,它会触发Selected事件处理程序,我可以使用myGridView.SelectedDataKey.Value获取所选行的DataKey列的值。

但是,行EditedDeleted时的事件处理程序似乎没有一种机制来获取相关行的DataKey值。这些事件处理程序的事件arg参数包含GridView中行的索引,但我特别在DataKey值之后。

通过实用程序方法重新获取对象列表以及从事件arg参数获取的索引不是一个选项,因为对象列表可能已更改。

有人能告诉我怎么做吗?

TIA

4 个答案:

答案 0 :(得分:17)

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

答案 1 :(得分: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);
   }
 }

答案 2 :(得分: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);

你在gridview的回发中获得了datakey值。

答案 3 :(得分:0)

您可以使用从编辑/删除事件返回的索引号,然后选择行手动

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