C# for循环获取DataGridView数据报索引超出数组界限解决
报错原因
- 直接触发异常的核心问题:代码中
string[] DataGridViewArray = { }声明的是长度为0的空数组,没有分配任何可存储元素的内存空间。循环第一次执行到DataGridViewArray[i]赋值逻辑时,i为0,但空数组不存在索引0的位置,立刻抛出索引越界异常。 - 代码还存在两个未触发的隐藏问题:
- 数组赋值完成后调用
DataGridViewArray.ToString(),数组的默认ToString方法只会返回类型名称System.String[],不会输出数组内存储的实际内容,无法实现文本框展示数据的需求。 - DataGridView默认开启
AllowUserToAddRows属性,此时Rows.Count会将底部供用户新增数据的空白行计入总数,该行首单元格值为null,直接调用ToString会触发空引用异常。
- 数组赋值完成后调用
修正实现
优先推荐使用List<string>动态存储数据,无需提前计算长度,同时兼容空值、新增行场景,代码如下:
List<string> firstCellValues = new List<string>(); for (int i = 0; i < DataGridView1.Rows.Count; i++) { DataGridViewRow currentRow = DataGridView1.Rows[i]; // 跳过自动生成的新增行、单元格值为空的行 if (currentRow.IsNewRow || currentRow.Cells[0].Value == null) continue; firstCellValues.Add(currentRow.Cells[0].Value.ToString().Trim()); } // 按需选择拼接分隔符,示例用换行分隔,也可以换成逗号、空格等 textBox1.Text = string.Join(Environment.NewLine, firstCellValues);
如果必须使用数组实现,需要在初始化数组时指定匹配有效数据行的长度,参考代码:
// 先统计有效数据行总数,排除自动新增行 int validRowCount = 0; foreach (DataGridViewRow row in DataGridView1.Rows) { if (!row.IsNewRow) validRowCount++; } string[] DataGridViewArray = new string[validRowCount]; int arrayIndex = 0; for (int i = 0; i < DataGridView1.Rows.Count; i++) { DataGridViewRow currentRow = DataGridView1.Rows[i]; if (currentRow.IsNewRow || currentRow.Cells[0].Value == null) continue; DataGridViewArray[arrayIndex] = currentRow.Cells[0].Value.ToString().Trim(); arrayIndex++; } textBox1.Text = string.Join(Environment.NewLine, DataGridViewArray);
内容的提问来源于stack exchange,提问作者smiley rainbow
相关产品推荐
相关产品推荐

