-2

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.

Yuki
  • 31
  • 8
  • 5
    Duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Bjørn-Roger Kringsjå Dec 09 '15 at 05:46
  • What is the value of *i* when the exception occurs? Do you have enough controls? – JerryM Dec 09 '15 at 21:35
  • An error occured even write one line without looping. Like this: >Me.Controls("Textbox" & 1).Text = "1234" – Yuki Dec 10 '15 at 06:27

1 Answers1

1

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.

davidallyoung
  • 1,204
  • 13
  • 14
  • I put all textboxs on panel.I think the problem is not looping.I met NullReference exception, even write just like this: > Me.Controls("Textbox" & 1).Text = "1234" – Yuki Dec 10 '15 at 06:51
  • OH MY GOD! I can't believe it... I wrote: >Panel.Controls("Textbox" & 1).Text = "1234" is WORK.. How STUPID I am! Thank you for your answer @DavidY – Yuki Dec 10 '15 at 07:10
  • It happens :). Enjoy. – davidallyoung Dec 10 '15 at 14:22