C#中编程添加DataGridViewRow报索引超出范围错误如何解决
错误触发原因
异常抛出在dataGridView1.Rows[0]这一行,核心原因是执行代码时dataGridView1的行集合为空,不存在索引为0的行。
之前代码能正常运行,通常是因为DataGridView默认开启AllowUserToAddRows属性,初始状态下会自动生成一个供用户输入的空白占位行,此时Rows[0]是存在的。当出现以下任意一种情况时,就会触发越界:
- 手动关闭了
AllowUserToAddRows属性,控件初始状态没有任何预生成的行 - 代码执行前调用过
Rows.Clear()清空了所有行,且没有剩余可访问的行 - 控件绑定了空数据源,还未生成任何可见行
- 控件还未完成初始化,行集合尚未加载
修复方案
选择任意一种适配场景的方案即可:
- 方案1:不依赖现有行,直接基于控件列结构创建新行(最稳定,不受现有行数量影响)
DataGridViewRow row = new DataGridViewRow(); // 按照DataGridView的列配置初始化单元格结构 row.CreateCells(dataGridView1); row.Cells[0].Value = "AbC"; row.Cells[1].Value = 123; dataGridView1.Rows.Add(row);
- 方案2:保留克隆行的逻辑,增加行存在性判断
DataGridViewRow row; if (dataGridView1.Rows.Count > 0) { row = (DataGridViewRow)dataGridView1.Rows[0].Clone(); } else { row = new DataGridViewRow(); row.CreateCells(dataGridView1); } row.Cells[0].Value = "AbC"; row.Cells[1].Value = 123; dataGridView1.Rows.Add(row);
- 方案3:直接传入单元格值新增行(写法最简洁,不需要手动构造行对象)
// 按列的索引顺序依次传入对应单元格的值即可 dataGridView1.Rows.Add("AbC", 123);
注意:如果DataGridView是数据绑定模式(绑定了DataTable、IBindingList等数据源),不要直接通过Rows集合添加行,需要操作对应数据源新增记录,否则会触发额外异常。
内容的提问来源于stack exchange,提问作者Abbas
相关产品推荐
相关产品推荐

