Walter Wouters
Walter Wouters

Reputation: 11

Update NumericUpDown.Maximum from corresponding txt.text control using for each loop

As newbie in VBA.net i want to solve following.

I have a form with 38 text controls in 4 groupboxes. These get filled by clicking a row in a datagridview. I have 38 corresponding NUD's where i want the maximum to be equal to its corresponding text. A 'pair' is always in one of the 4 groupboxes. Besides that there are also textboxes on the form itself to control the DGV.

I have a naming convention that makes it possible to match them easily . NUDGeel corresponds with txtGeel , NUDRood with TxtRood, NUDGroen with txtGroen etc et

Now that update is easily done if you do them one by one

NUDGeel.maximum = txtGeel.text
NUDRood.maximum = txtRood.text
etc

What i want to achieve is that this gets done in a for each loop. (Order to prevent me typing this 38 times (and also just to 'understand' it)

I can figure out how to start the loop

Dim c As Control
For Each c In Me.Controls
    If TypeName(c) = "NumericUpDown" Then
    'do some magic
    End If
Next

I have tried to search for the magic code, and i guess from research it is pretty simple, i just donot get it .

Anyone with an idea how to fix ?

Upvotes: 0

Views: 51

Answers (2)

F0r3v3r-A-N00b
F0r3v3r-A-N00b

Reputation: 3003

Private Sub SetMaximum()
    Dim controlNames() As String = {
        "Geel", "Rood", "Name1", "Name2", ' list all the names of your controls here excluding NUD/txt
        }

    For Each controlName As String In controlNames
        CType(Me.Controls("NUD" & controlName),NumericUpDown).Maximum = CType(Me.Controls("txt" & controlName),TextBox).Text
    Next
End Sub

This assumes that all the controls are not inside any containers. If they are, you must use the container (panel, groupbox, etc) instead of Me.

Upvotes: 0

John
John

Reputation: 3182

For Each tb In Controls.OfType(Of TextBox)
    Dim nud = DirectCast(Controls(tb.Name.Replace("txt", "NUD")), NumericUpDown)

    If nud IsNot Nothing Then
        nud.Maximum = CDec(tb.Text)
    End If
Next

You don't need the If statement if there are no other TextBoxes on the form besides those with corresponding NumericUpDowns.

Upvotes: 1

Related Questions