J. McMahon
J. McMahon

Reputation: 3

How to stop an 'Object reference not set to an instance of an object' when creating textboxes at run time in VB

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.

Upvotes: 0

Views: 67

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460340

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.

Upvotes: 2

Related Questions