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
相关产品推荐
相关产品推荐

