【问题标题】:gridview delete event not workinggridview删除事件不起作用
【发布时间】:2012-10-23 07:30:41
【问题描述】:

我有一个带有自动生成的删除按钮的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# 中的一个很好的例子可以完成这项工作,将不胜感激。

【问题讨论】:

  • 调试器中什么也没有出现。

标签: c# asp.net gridview


【解决方案1】:

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

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

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(); 
}

【讨论】:

    【解决方案2】:

    这是我为使其正常工作所做的:

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

    【讨论】:

    • 我刚试过你的代码,我发现索引超出了范围。这可能很疯狂,但它确实有效。 selectedIndex 设置为 -1。我不知道为什么这不起作用。如果您不添加 .ToString(),加上您的第一行代码抛出和错误。另外,我只是在学习如何手动编写网格而不是使用向导。
    【解决方案3】:

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

    【讨论】:

    • 这就是我的想法,但它在 rowupdating 事件中有效。我已将索引设置为 1,结果相同。
    • 我认为这太明显了:-)。哪一行实际抛出异常?
    猜你喜欢
    • 2010-09-06
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多