是否可以为每个语句传递一组文本框名称

is it possible to pass a group of textbox names to for each statement

我有一个包含 7 个文本框的表单,我喜欢使用“For Each”语句处理其中的值,因此我使用了以下代码,在其中我定义了一个包含文本名称的字符串数组框并将其成员传递给“me.controls()”,错误会在带有以下语句的行上触发:“对象引用未设置为对象的实例”

 Dim grades() As String = {"sa", "sb", "sc", "sd", "ss", "sr", "st"}

            Dim x As String = InputBox("what is the multiplier", "Enter Value", "1")
            For Each s In grades
                If Not String.IsNullOrEmpty(Me.Controls(s).Text) Then
                    Me.Controls(s).Text = Math.Round(CDbl(Me.Controls(s).Text) * CDbl(x))
                End If
            Next

完成此任务的最佳方法是什么?谢谢

既然可以传递 TextBoxes 本身,为什么还要传递 TextBoxes 的名称?假设您在设计器中添加了 TextBoxes,每个字段都生成了一个字段,因此请使用这些:

Dim textBoxes = {sa, sb, sc, sd, ss, sr, st}

For Each textBox In textBoxes
    'Use textBox here.
Next

除了按照 jmcilhinney 的建议从文本框本身(而不是它们的名称)创建数组外,我建议您使用 Double.TryParse() 来确定用户输入的乘数和成绩是否实际上是有效的双精度数在尝试与他们一起做数学之前。这将防止 运行 次错误输入的异常:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim grades() As TextBox = {sa, sb, sc, sd, ss, sr, st}

    Dim x As Double
    Dim strX As String = InputBox("what is the multiplier", "Enter Value", "1")

    If Double.TryParse(strX, x) Then
        For Each s In grades
            Dim grade As Double
            If Double.TryParse(s.Text, grade) Then
                s.Text = Math.Round(grade * x)
            End If
        Next
    Else
        MessageBox.Show("Invalid Multiplier")
    End If
End Sub