Question Only Last Button Works

Vegito_ZA

Member
Joined
Mar 4, 2016
Messages
8
Programming Experience
Beginner
Hi,

I have created a dynamic form with an Update button. I have declared the following global variable:
VB.NET:
WithEvents btnUpdate As Button
and later in a loop the following
VB.NET:
btnUpdate = New button
...
Me.Controls.Add(btnUpdate)
And Finally
VB.NET:
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
UpdateForm.tbRef.Text = Me.tbRef.Text
UpdateForm.Show()
End Sub
[FONT=Consolas][SIZE=2][COLOR=#dcdcdc][FONT=Consolas][SIZE=2][COLOR=#dcdcdc][FONT=Consolas][SIZE=2][COLOR=#dcdcdc]
[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT]

My Problem is:

The code generates the correct layout and the correct controls, but only the last Update button generated works. What am I doing wrong?
Any help would be greatly appreciated.
 
A variable can only have one value, so btnUpdate will only refer to one object. To handle events for multiple runtime generated controls use AddHandler statement.
 
The button Problem is now solved. How do I link the contents of each textbox (tbRef) to the button generated along with it?
No matter what I try, as before, all the buttons refer to the last textbox generated.
VB.NET:
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
UpdateForm.tbRef.Text = Me.tbRef.Text
UpdateForm.Show()
End Sub
 
The sender event parameter is the object that raised the event. Parameter type is Object and you can cast that to an appropriate type of object, such as Button, with CType/DirectCast.
 
Sorry, I am still learning VB and all the tutorials I find just give examples of string to integer conversions and vice versa. Could you possibly point me towards a tutorial that uses these operators in a similar context to what I'm trying to do?
 
just give examples of string to integer conversions and vice versa
Does it really matter which type it is, or what value or object it is?

CType Function (Visual Basic)
dim abutton = ctype(sender, button)

DirectCast Operator (Visual Basic)
dim abutton = directcast(sender, button)
 
Back
Top