VB.NET读取DataGridView指定单元格值触发索引越界错误,求解决方案
问题:读取DataGridView指定单元格值时触发索引越界异常
我需要读取3列3行DataGridView中指定单元格(示例为2x2位置)的值,尝试了以下代码后,Visual Studio抛出错误:
"mscorlib.dll中发生未处理的'System.ArgumentOutOfRangeException'异常"
附加信息:"索引超出范围。必须为非负值且小于集合大小。"
我的代码:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'read array and send to DataGridView Dim cella(3, 3) As String cella(0, 0) = "Papa" cella(0, 1) = "Mamma" cella(0, 2) = "Bimbo1" cella(0, 3) = "Bimbo2" cella(1, 0) = "Bianco" cella(1, 1) = "Rosso" cella(1, 2) = "Nero" cella(1, 3) = "Blu" cella(2, 0) = "Firenze" cella(2, 1) = "Pisa" cella(2, 2) = "Livorno" cella(2, 3) = "Empoli" cella(3, 0) = "Gatto" cella(3, 1) = "Cane" cella(3, 2) = "Panda" cella(3, 3) = "Macaco" For x As Integer = 0 To 3 DataGridView1.Columns.Add("newColumnName", "Testo") Next For y As Integer = 0 To cella.GetUpperBound(0) DataGridView1.Rows.Add(cella(0, y), cella(1, y), cella(2, y), cella(3, y)) Next End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'Create MsgBox with the value of the specified cell MsgBox(DataGridView1.SelectedRows.Item(2).Cells(2).Value.ToString()) End Sub
请问为何会出现该错误?如何正确读取指定单元格的值?
解答
错误原因
- SelectedRows集合为空:你用
DataGridView1.SelectedRows.Item(2)尝试访问选中行集合的第3个元素,但默认情况下没有行被选中,SelectedRows集合长度为0,直接访问索引2必然触发越界异常。 - DataGridView实际行列数与预期不符:你的Button1_Click代码中,数组定义为
(3,3)(对应4x4的元素),循环添加了4列和4行,但你预期的是3列3行,索引逻辑混乱。
正确实现方式
1. 直接读取指定位置的单元格
不需要依赖选中行,直接通过Rows和Cells的索引访问(注意:DataGridView的行、列索引从0开始,2x2位置对应第3行第3列):
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ' 先判断目标行列是否存在,避免越界 If DataGridView1.Rows.Count > 2 AndAlso DataGridView1.Columns.Count > 2 Then Dim cellValue = DataGridView1.Rows(2).Cells(2).Value ' 判断单元格是否为空 If cellValue IsNot Nothing Then MsgBox(cellValue.ToString()) Else MsgBox("该单元格为空") End If Else MsgBox("指定位置的行或列不存在") End If End Sub
2. 修正DataGridView的初始化代码(如果确实需要3列3行)
调整数组和循环逻辑,创建符合预期的3列3行表格:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' 定义3x3的数组,索引范围0-2 Dim cella(2, 2) As String cella(0, 0) = "Papa" cella(0, 1) = "Mamma" cella(0, 2) = "Bimbo1" cella(1, 0) = "Bianco" cella(1, 1) = "Rosso" cella(1, 2) = "Nero" cella(2, 0) = "Firenze" cella(2, 1) = "Pisa" cella(2, 2) = "Livorno" ' 添加3列 For x As Integer = 0 To 2 DataGridView1.Columns.Add($"Column{x}", $"列{x+1}") Next ' 添加3行 For y As Integer = 0 To cella.GetUpperBound(0) DataGridView1.Rows.Add(cella(y, 0), cella(y, 1), cella(y, 2)) Next End Sub
内容的提问来源于stack exchange,提问作者Marco Giglio
相关产品推荐
相关产品推荐

