0

For a project I require the creation of textboxes at run time, to this end I have used this code;

Dim AOP As Integer = GlobalVariables.AOP
Dim tb(11, 11) As TextBox
Dim LocationX As Integer
Dim LocationY As Integer
Dim count As Integer = 2

LocationX = 10
LocationY = 10
tb(1, 0).Name = "txtRoot"
tb(1, 0).Size = New Size(170, 20)
tb(1, 0).Location = New Point(LocationX, LocationY)
tb(1, 0).Visible = False

I am then able to loop it using this For loop;

For i = 1 To AOP
        If count > AOP Then

        Else
            If i = AOP Then
                LocationY = LocationY + 10
                LocationX = 10
                tb(count, 0).Name = "txtXValue" & 0 & "YValue" & count
                tb(count, 0).Size = New Size(170, 20)
                tb(count, 0).Location = New Point(LocationX, LocationY)
                Controls.Add(tb(count, 0))
                count = count + 1
                i = 1
            Else
                LocationX = LocationX + 10
                tb(count, i).Name = "txtXValue" & i & "YValue" & count
                tb(count, i).Size = New Size(170, 20)
                tb(count, i).Location = New Point(LocationX, LocationY)
                Controls.Add(tb(count, i))
            End If
        End If
Next

This works in theory, however, when the code reaches the line;

tb(1, 0).Name = "txtRoot"

It returns the error 'Object reference not set to an instance of an object' I am wondering if there is anyway around this? or if this way of creating textboxes isn't possible? Any help would be appreciated.

Fred
  • 5,368
  • 4
  • 38
  • 67
  • You do not create any textboxes in this code. You do create `Point`s and `Size`s though. – GSerg Oct 23 '15 at 08:26
  • What is the value of GlobalVariables.AOP? – Han Oct 23 '15 at 08:26
  • Possible 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) – GSerg Oct 23 '15 at 08:27
  • The value of GlobalVariables.AOP is set by a textbox on another form, it can be anything from 1 to 10 – J. McMahon Oct 23 '15 at 08:27

1 Answers1

2

You have initialized the array but not added initialized TextBoxes, the array contains currently only Nothing. Also note that arrays are zero based, so the first TextBox is in tb(0, 0).

For i As Int32 = 0 To tb.GetLength(0) - 1
    For ii As Int32 = 0 To tb.GetLength(1) - 1
        tb(i, ii) = New TextBox()
        tb(i, ii).Visible = False
        ' .... '
    Next
Next

Now all are initialized.

Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859