0

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

我看过很多教程和例子。这段代码应该可以正常工作吗?

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# 中的一个很好的例子可以完成这项工作,那将不胜感激。

4

3 回答 3

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 选项不起作用。无论如何,它现在正在工作。

于 2012-11-02T16:16:42.090 回答
0

听起来您 DataKeyNames="rec_id"在 gridview aspx 中没有设置?如果您没有让页面知道它们是什么,则无法访问数据键

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

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(); 
}
于 2012-11-02T15:56:43.900 回答
0

我可能误解了您的问题,但根据此处EditIndex 属性是从零开始的,因此您不能将其设置为-1。将其设置为该值将引发 ArgumentOutOfRangeException。

于 2012-11-02T15:57:49.880 回答