索引超出范围错误求助:修改DataGridView第5列单元格触发异常
DataGridView索引越界问题解决办法
核对列索引计数规则:DataGridView的列索引从0开始,你要修改的第5列对应的索引是4,而非代码里的5。如果你的DataGridView实际只有5列(索引0-4),访问
Cells(5)就会触发索引越界错误,把代码中的Cells(5)替换成Cells(4)即可。排除空白新行:DataGridView默认允许用户添加新行(
AllowUserToAddRows属性为True),这行空白行会被计入RowCount,但它的单元格可能未完全初始化。循环时可以排除这一行:Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click For item As Integer = 0 To Employee_Shift_DetailDataGridView.RowCount - 2 Employee_Shift_DetailDataGridView.Rows(item).Cells(4).Value = "001" Next End Sub或者先临时关闭添加新行功能,完成赋值后再开启:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Employee_Shift_DetailDataGridView.AllowUserToAddRows = False For item As Integer = 0 To Employee_Shift_DetailDataGridView.RowCount - 1 Employee_Shift_DetailDataGridView.Rows(item).Cells(4).Value = "001" Next Employee_Shift_DetailDataGridView.AllowUserToAddRows = True End Sub确认列的实际数量:可以添加调试代码验证列数,确保目标索引在有效范围内:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Debug.WriteLine("当前列数:" & Employee_Shift_DetailDataGridView.Columns.Count) ' 后续循环代码 End Sub运行后查看输出的列数,如果列数≤5,说明
Cells(5)确实超出了有效索引范围。
内容的提问来源于stack exchange,提问作者Arm Lion
相关产品推荐
相关产品推荐

