uramium
uramium

Reputation: 17

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

I have a form with 7 Text Boxes and I like to process the values in them by using "For Each" statement , so I used the following code in which i defined an array of string containing the names of the text boxes and pass its members to "me.controls()" , error fires on the line with this statement : "Object reference not set to an instance of an object"

 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

what is the best method to accomplish this ? Thank you

Upvotes: 0

Views: 45

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39152

In addition to creating an array from the TextBoxes themselves (instead of their names) as suggested by jmcilhinney, I recommend you use Double.TryParse() to determine if the multiplier and grades entered by the user are actually valid doubles before attempting to do math with them. This will prevent run-time exceptions from bad input:

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

Upvotes: 1

jmcilhinney
jmcilhinney

Reputation: 54477

Why would you pass the names of the TextBoxes when you can pass the TextBoxes themselves? Assuming that you added the TextBoxes in the designer, a field was generated for each one, so use those:

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

For Each textBox In textBoxes
    'Use textBox here.
Next

Upvotes: 1

Related Questions