Add values to multiple textboxes (similar names)

2019-09-26 06:59发布

问题:

I was trying to find the solution for this but nothing works. I have around 650 textboxes named : A001A, A002A...A600A and I would like to put values in those texboxes for instance "example value".

I've found solution to put values in all textboxes in a form, but in mine there are those with some other values.

Next solution is this one :

    Dim textBoxArr() As TextBox = {A2, A3, A4, A5, etc..}
For Each tb As TextBox In textBoxArr
    Select Case tb.Text
        Case "RESNO"
            tb.Text = "-15,55,0"
        Case "DOGAL"
            tb.Text = "-15,54,0"
    End Select
Next

...again I have to input all names and I don't have enough freedom to manipulate values for first 50 and so on.

This is the code I have and it doesn't work:

For I As Integer = 0 To 650
    Dim txt As TextBox = DirectCast(Me.Controls("A00" & I.ToString & "A"), TextBox)
            txt.Text = "example value"
Next

error: object reference not set to an instance of an object

Thanks for the help.

EDIT : I have found the solution from user Idle_Mind

Dim matches() As Control
For i As Integer = 1 To 650
    matches = Me.Controls.Find("A" & String.Format("{0:000}", i) & "A", True)
    If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
        Dim cb As TextBox = DirectCast(matches(0), TextBox)
        If cb.Text = "" Then
            cb.Text = "test"
        End If
    End If
Next

回答1:

You aren't testing for the right key (if your TextBoxes are properly named).

Try it like this:

For i As Integer = 1 To 650
  Dim key As String = "A" & String.Format("{0:000}", i) & "A"
  If Me.Controls.ContainsKey(key) Then
    Me.Controls(key).Text = "blah"
  End If
Next