user2879745
user2879745

Reputation: 11

How to call upon dynamically created objects

Okay so here is what I have:

    Do
        x = x + 1
        Dim myTxt As New TextBox
        myTxt.Name = ("TbMat" & x.ToString())
        myTxt.Location = New Point(13, 13 + (x * 37))
        myTxt.Tag = "For DB"
        myTxt.Visible = True
        Button2.Location = New Point(13, 39 + (x * 37))
        If x = 5 Then
            Button1.Dispose()
        End If
        Me.Controls.Add(myTxt)
        Me.Refresh()
    Loop Until x >= 1

It's my makeshift way of letting the user add a textbox by clicking a button. I am new to programming so this may be an easy fix but here is my question... when the user adds a textbox I want the first one to be "TbMat1" so I would assume to call upon it to get information I would just use, for example, textbox1.text=TbMat1.text. When I do this, it says TbMat1 is not declared, which is obvious since it isn't created yet.

I need help pulling information from the new textboxes to other textboxes, and later I will figure out exporting. Thanks.

Upvotes: 1

Views: 815

Answers (1)

When you created the control, you created it as myTxt which is its object reference. So in the procedure where that code block exists this would work:

 SomeOtherTB.Text = myTxt.Text

The name is just the name, not an object reference or 'handle'. Further, once the code exits that procedure myTxt goes out of scope because that is where it was declared (Dim or Private|Friend|Public). To access your new control elsewhere:

SomeOtherTB.Text = Me.Controls("TbMat1")       ' or "TbMat" & x.ToString()

OR create a new object ref if you want:

Friend myTB AS TextBox                        ' module level at least

myTb = Me.Controls("TbMat1") 

The latter might not be practical if you are making lots of them.

Upvotes: 2

Related Questions