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

Time:08-11

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

I have a form with 38 text controls. 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. I have a naming convention that makes it possible to match them easily . NUDGeel corrsponds with txtGeel , NUDRood with TxtRood, NUDGroen with txtGroen etc et

Now that 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 ?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related