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

索引超出范围错误求助:修改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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:05:14