首页 > 解决方案 > 错误:在 gridview 中更新多行时索引超出范围

问题描述

我正在尝试使用单个按钮单击更新网格视图上的多行,但是在前 10 次完成更新后,它会抛出此错误消息索引超出范围。必须是非负数且小于集合的大小。参数名称:索引。我在 gridview 上有一个页面计数和页面索引,但它没有移动到下一页来完成更新。

 protected void Clear_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(DB);

        string name = HttpContext.Current.User.Identity.Name; //Gets current User.
       

        int a = 0;

       

        #region Update Barcode 

        DataTable TableP = (DataTable)ViewState["Product"];

        for (int i = 0; i < TableP.Rows.Count; i++)
        {
            Label barcode = (Label)Product.Rows[a].Cells[0].FindControl("Barcode");
            Label barcodeLocation = (Label)Product.Rows[a].Cells[1].FindControl("barcodeLocation");
            Label batchID = (Label)Product.Rows[a].Cells[4].FindControl("batchID");
            Label upc = (Label)Product.Rows[a].Cells[5].FindControl("UPC");

            SqlCommand cmd = new SqlCommand("spUpdateBarcode", con);

            con.Open();
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@BarcodeNo", barcode.Text);
            cmd.Parameters.AddWithValue("@userId", name);
            cmd.Parameters.AddWithValue("@lastupdate", DateTime.Now);
            cmd.Parameters.AddWithValue("@batch", batchID.Text);
            cmd.Parameters.AddWithValue("@BarcodeLocation", barcodeLocation.Text);
            cmd.Parameters.AddWithValue("@UPC", upc.Text);

            cmd.ExecuteNonQuery();
            con.Close();

            a++;
        }


        GetBarcodeDetails();

        #endregion

       



    }

标签: asp.net

解决方案


这里的问题是,您想要更新数据表行中存在的所有行,而您没有将这些行绑定到GridView控件,这意味着您不能更新比绑定到GridView.

为此,您将不得不通过禁用分页来绑定所有行(如果您有很多记录,则不建议这样做),或者您应该手动更新您的对象DataSource,以防万一DataTable。您修改它然后将其绑定到GridView.

您需要遍历唯一的绑定元素,因为我看到您正在从 gridview 列中获取值。这将仅更新绑定的行,但不会导致异常,因为它仅循环通过绑定到的索引GridView

将循环更改为仅通过绑定行:

for (int i = 0; i < Product.Rows.Count; i++)
{
    // your code.
}

推荐阅读