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.

4
  • You do not create any textboxes in this code. You do create Points and Sizes though. Commented Oct 23, 2015 at 8:26
  • What is the value of GlobalVariables.AOP? Commented Oct 23, 2015 at 8:26
  • Possible duplicate of What is a NullReferenceException and how do I fix it? Commented Oct 23, 2015 at 8:27
  • The value of GlobalVariables.AOP is set by a textbox on another form, it can be anything from 1 to 10 Commented Oct 23, 2015 at 8:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.