TensE
TensE

Reputation: 49

VB.Net How can I loop an If statement with multiple variables?

So if I have lets say 10 textboxes I need to fill I have to repeat a loop 10 times and each time add to a different text box. Right now I have something like this:

    If i = 0 Then
        Shift0 = endTime - startTime
        textStart0.text = startTime
        textEnd0.text = endTime
        chkBox0.checked = True
    End If

I have I repeating like that 8 more times to make 9. I want to make it so that the loop would increase the number from 0-9 every time it goes through

    If i = (x) Then
        Shift(x) = endTime - startTime
        textStart(x).text = startTime
        textEnd(x).text = endTime
        chkBox(x).checked = True
    End If
    x = x + 1

How can I put it in the loop so that the number in the name of the object increased with every loop?

Upvotes: 0

Views: 646

Answers (3)

Jxx
Jxx

Reputation: 1064

You can use the Controls property of a Control with an index. If your form contains exactly and only 10 textboxes, this will work fine:

For i as Integer = 1 to 10
    Form1.Controls(i).Text = "Box " + i.ToString()
Next

If you have other controls in the form you have no guarantee over the index (you can't reply on 1 to 10 being the textboxes as your design progresses). Therefore, I'd recommend you put them inside a panel and refer to this panel's Controls:

For i as Integer = 1 to 10
    Panel1.Controls(i).Text = "Box " + i.ToString()
Next

To learn more about loops in VB.NET, start here: http://www.tutorialspoint.com/vb.net/vb.net_loops.htm

Upvotes: 0

Grim
Grim

Reputation: 672

Control arrays are a thing of the past, from the VB6 days, unfortunately, as you've discovered, they can still have their uses! Try this for your loop;

For i = 0 to 9
    Shift0 = endTime - startTime                     ' Is Shift0 a control!?
    FindControl("textStart" & i).Text = startTime
    FindControl("textEnd" & i).Text = endTime
    FindControl("chkBox" & i).Checked = True
Next

With this function to help...

Private Function FindControl(pName As String) As Control
    Dim vMatches = Me.Controls.Find(pName, True)
    If vMatches IsNot Nothing AndAlso vMatches.Length > 0 Then Return vMatches(0)
    Throw New Exception("Could not find the specified control!")
End Function

Having said all that, I would strongly recommend re-thinking how your form and application work to avoid this!

Upvotes: 2

stato74
stato74

Reputation: 110

Something like this would work

For x = 0 to 9
    Shift(x) = endTime - startTime
    textStart(x).text = startTime
    textEnd(x).text = endTime
    chkBox(x).checked = True
next x

Upvotes: 1

Related Questions