简体   繁体   中英

Why I can't reference textbox name vb.net

I want to add value from array to each textbox.
Here is my code:

For i as int32 = 0 To Array.length - 1
    Me.Controls("TextBox" & i + 1).Text = Array(i)
Next

When I run above code, I got the NullReferenceException error.
Error Line is:

Me.Controls("TextBox" & i + 1).Text = Array(i)

I tried another code after searching from the web,

For i as int32 = 0 To Array.length - 1
    Dim c as Control() = Me.Controls.Find("TextBox" & i + 1 , True)
    If c.Length = 1 Then
        Me.Controls("TextBox" & i + 1).Text = Array(i)
    End If
Next

But it still doesn't work. Please help me... Thanks in advanced.

Find can return Null (nothing) if it doesn't find a result, which is causing your null reference exception.

As for enumerating/looping over your textbox controls:

Try explicitly looping over them using a foreach on your controls collection

    For Each control In Me.Controls
        If control.GetType() Is GetType(TextBox) Then
            'Do stuff to control.
        End If
    Next

The process you're using now of attempting to map to the name of the control is not going to be very adaptable, especially if someone else comes a long and changes the name of the control.

If there are only a certain set of textboxes you want to update, you could put them in a panel on the form, and use the same method described above to loop through the panel's controls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM