不能在循环内使用变量计数器

cant use variable counter inside loop

我在 vb.net

中将数据库连接到我的应用程序

如果我想从任何行或列中获取值,我会使用这段代码,它工作正常

DataGridView1.Rows(1).Cells(1).Value.ToString

我的问题是我有 table 包含 14 行,我想循环检查每行中的第一个单元格是否包含特定值以执行其他任务

如果我在计数器中使用变量 i 我得到一个错误

在此代码中

    Private Sub Button24_Click(sender As Object, e As EventArgs) Handles Button24.Click


Dim see As String

For i As Int32 = 0 To 14

        see = DataGridView1.Rows(i).Cells(1).Value.ToString

        If see = "FLOWRATE" Then

        TextBox11.Text = TextBox11.Text & see & "  "

        End If

Next

End Sub

当我按下按钮时出现此错误

An unhandled exception of type 'System.NullReferenceException' occurred in project1.exe

Additional information: Object reference not set to an instance of an object.

我怀疑你的意思是 For i As Int32 = 0 To 13,而不是 14。14 意味着有 15 行,因为事情是从零开始的。

你可以简单地这样做而不是硬编码行数,而是做这样的事情:

For i As Int32 = 0 To DataGridView1.Rows.Count - 1
    'Handle each row
Next

这个错误是因为我引用的行不存在。

行的索引可能是从 1 到 14 或 0 到 13。

您必须适应循环边界