Jad Jad - 1 year ago 50
Vb.net Question

Huge amount of textboxes repeated code

I have around 200 textboxes in my form.
Pressing "Enter" takes you to the next textbox.
Pressing "Up" takes you to the upper textbox, etc...
I know the coding but it's 200 textboxes so it's gonna be a huge amount of Copy/Paste. Is there any short way i can do it for all the 200 textboxes ?

Answer Source

You really want to show the users 200 textboxes on a single form? You should at least group them in a container control logically, for example in a Panel. Then you could use OfType.

You could add this to the constructor of your form-class which uses anonymous event handler:

Dim allTextBoxes = from txt in Me.TextBoxPanel.Controls.OfType(Of TextBox)()
                   Order by txt.TabIndex
Dim txtList = allTextBoxes.ToList()

For i As Int32 = 0 To txtList.Count - 1
    Dim thisTxt = txtList(i)
    Dim nextIndex = If(i + 1 >= txtList.Count, 0, i + 1)
    Dim prevIndex = If(i - 1 < 0, txtList.Count - 1, i - 1)
    Dim nextTxt = txtList(nextIndex)
    Dim prevTxt = txtList(prevIndex)

    AddHandler thisTxt.KeyDown, 
        Sub(txt As Object, e As KeyEventArgs)
            If e.KeyCode = 38 Then 'up
                Me.ActiveControl = prevTxt
            ElseIf e.KeyCode = 13 Then 'enter
                Me.ActiveControl = nextTxt
            End If
        End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download