vb.netwinformsctypedirectcast

In A Dynamic Form, How do I link the contents of a textbox (tbRef) to the button generated along with it?


I am still learing VB and have run into a problem with no decent tutorial. I have created a dynamic form that generates a Textbox and a Update button in each cycle of a loop.

I have declared the following global variables:

Dim tbRef As Textbox
WithEvents btnUpdate As Button

and later in the loop the following

Do Until counter = Maxrows 

counter = counter + 1
...
tbRef = New TextBox
...
Me.Controls.Add(tbRef)


btnUpdate = New button
...
AddHandler btnUpdate.Click, AddressOf btnUpdate_Click
Me.Controls.Add(btnUpdate)
...
tbRef.Text = ds.Tables("Records").Rows(counter - 1).Item(0)

Loop

And Finally

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
UpdateForm.tbRef.Text = Me.tbRef.Text
UpdateForm.Show()
End Sub

My Problem is:

The code generates the correct layout and the correct controls, and the button works fine if only one result is returned. If there is more than one button created, all the buttons refer to the contents of the last Textbox generated. The Only answer I got on the internet was that I must somehow use Ctype/DirectCast to cast the contents of each textbox to the button generated with it, but I cant find any tutorial on how to use these Operators in this context. Any help would be greatly appreciated.


Solution

  • As an option, you can use Tag property of button and store a reference to the text box in the tag property. Then when you want to find the textbox which the button is responsible for, you can unbox the text box from tag property of the button using DirectCast. The button itself is in sender parameter of the method which handles the event.

    You also can assign a name to the text boxes and store the name in tag property and then find the control using that name.

    For example

    For index = 1 To 10
        Dim txt = New TextBox()
        'Set other properties
        'Add it to form
    
        Dim btn = New Button()
        btn.Tag = txt
        AddHandler btn.Click, New EventHandler(AddressOf btn_Click)
        'Set other properties
        'Add it to form
    Next
    

    The you can handle the event this way:

    Private Sub btn_Click(sender As Object, e As EventArgs)
        Dim btn = DirectCast(sender, Button)
        Dim txt = DirectCast(btn.Tag, TextBox)
        MessageBox.Show(txt.Text)
    End Sub