asp.net - 错误:在 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
}
解决方案
这里的问题是,您想要更新数据表行中存在的所有行,而您没有将这些行绑定到GridView
控件,这意味着您不能更新比绑定到GridView
.
为此,您将不得不通过禁用分页来绑定所有行(如果您有很多记录,则不建议这样做),或者您应该手动更新您的对象DataSource
,以防万一DataTable
。您修改它然后将其绑定到GridView
.
您需要遍历唯一的绑定元素,因为我看到您正在从 gridview 列中获取值。这将仅更新绑定的行,但不会导致异常,因为它仅循环通过绑定到的索引GridView
将循环更改为仅通过绑定行:
for (int i = 0; i < Product.Rows.Count; i++)
{
// your code.
}
推荐阅读
- python - 为什么我不能通过 BeautifulSoup 抓取亚马逊产品?
- php - 使用 Blogger API 和 PHP 设置描述、草稿和永久链接
- javascript - Javascript for loop 在计算 LCM 时给出无限循环错误
- javascript - 尝试从两个不同的文本输入中获取值并将它们放在同一个列表项中
- flutter - 将列表保存到 SharedPreferences
- c - 如何找出虚拟机的字长?
- c# - 如何确定从 ItemsControl 派生的类中的项目类型
- mysql - 在 WSL Ubuntu 18.04 上执行服务 mysql 重启时出现错误:没有目录,使用 HOME=/ 登录
- python - 如何从 Python 数据框中的 DateTimeIndex 中删除微秒?
- java - 这个片段有 O(log^2(n)) 复杂度吗?