gridview删除事件不起作用

时间:2012-11-02 15:47:09

标签: c# asp.net gridview

我有一个gridview,它有自动生成的删除按钮。网格有一个datakeyname,由于某种原因,我收到此错误:消息:索引超出范围。必须是非负数且小于集合的大小。参数名称:index

我看了很多教程和例子。这段代码应该正常吗?

protected void grdBins_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    int rec_id = int.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());

     SqlCommand cmd = new SqlCommand();
     cmd.CommandText = "delete from t_run_schedule_lots  " +
                       "where rec_id = @id";

     cmd.Parameters.Add("@id", SqlDbType.Int).Value = rec_id ;

     cmd.CommandType = CommandType.Text;
     cmd.Connection = this.sqlConnection1;
     this.sqlConnection1.Open();
     //execute insert statement
     cmd.ExecuteNonQuery();
     this.sqlConnection1.Close();
     //re-populate grid */
    fill_grid();
     grdBins.EditIndex = -1;
     grdBins.DataBind(); 
     // this bit was just to see if I was capturing the ID field properly. 
    lblBins.Visible = true;
     lblBins.Text = rec_id.ToString();
}

如果有人知道C#中的一个很好的例子可以使这项工作,我将不胜感激。

3 个答案:

答案 0 :(得分:0)

听起来你在gridview aspx中没有DataKeyNames="rec_id"? 如果您没有让页面知道它们是什么

,则无法访问datakeys

这是您的代码的重构版本。

protected void grdBins_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
       int rec_id = int.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
       using (SqlConnection conn = new SqlConnection(connectionString)){
            conn.Open();
            string cmdText = @"delete from t_run_schedule_lots
                               where rec_id = @id";
            using (SqlCommand cmd = new SqlCommand(cmdText, conn)){
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@id", rec_id);
                cmd.ExecuteNonQuery();
            }
       }
       grd.EditIndex = -1;
       fill_grid();
       grdBins.DataBind(); 
}

答案 1 :(得分:0)

我可能会误解你的问题,但根据here,EditIndex属性从零开始,所以你不能将它设置为-1。将其设置为该值将抛出ArgumentOutOfRangeException。

答案 2 :(得分:0)

以下是我为实现目标所做的工作:

GridViewRow row = (GridViewRow)grdBins.Rows[e.RowIndex];
            Label id = (Label)row.FindControl("Label9");

             SqlCommand cmd = new SqlCommand();
             cmd.CommandText = "delete from t_run_schedule_lots  " +
                               "where rec_id = @id";

             cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(id.Text) ;

虽然我不知道为什么RowIndex选项不起作用。无论如何它现在正在运作。