You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataGridView添加新行报错:索引不能为负或超出范围

DataGridView添加多行时索引越界问题解决方案

问题原因

原代码的核心问题是索引计算错误:

  • DataGridView的行索引从0开始,最大有效索引为Rows.Count - 1,直接用Rows.Count作为索引必然越界。
  • 当AllowUserToAddRows = true时,控件会自动在末尾添加一行空白的待编辑行,这行也会被计入Rows.Count,进一步导致索引偏移。

修复方案

不要依赖默认的空白行,主动调用Rows.Add()方法创建新行,直接操作新增的行即可避免索引问题:

// 主动添加新行并获取其索引
int newRowIndex = dataGridView1.Rows.Add();
DataGridViewRow newRow = dataGridView1.Rows[newRowIndex];

// 为新行的单元格赋值
newRow.Cells[0].Value = newRowIndex + 1; // 用索引+1作为序号,避免受默认行影响
newRow.Cells[6].Value = dt.Tables[0].Rows[0][0];
newRow.Cells[1].Value = dt.Tables[0].Rows[0][1];
newRow.Cells[3].Value = 1; // 数量
newRow.Cells[2].Value = dt.Tables[0].Rows[0][3];
newRow.Cells[7].Value = dt.Tables[0].Rows[0][2];

MessageBox.Show("سطر جديد");

额外优化

如果不需要用户手动添加行,可以关闭自动新增功能,避免默认空白行干扰计数:

dataGridView1.AllowUserToAddRows = false;

内容的提问来源于stack exchange,提问作者Abd Alrhman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 19:33:09