Reputation: 11
I have previously created buttons in my code, as shown:
Dim Itm As New Button
Itm.Name = "Itm" & i
Itm.Height = 62
Itm.Width = 159
Itm.Text = Temp(i, 0).ToUpper
Itm.Left = (F * 165)
Itm.Visible = True
Itm.BackColor = Colour
Itm.ForeColor = Color.Black
Me.pnlItemButton1.Controls.Add(Itm)
When I run the form, the buttons are created but I now need to create an Event Sub for when the new buttons are clicked. I have tried this:
Private Sub Itm1_click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Itm1.click
End Sub
But get an error that 'handle clause requires with WithEvent'
So how can i do this ?
Also, the amount of buttons - Itm(i) is variable, so how can i create a handle that will account for Itm1 to Itm99?
Upvotes: 0
Views: 574
Reputation: 313
For your first error, look at this. It may help you.
To create an event click for every button you create dynamically try this:
AddHandler Itm.Click, AddressOf Me.Itm1_Click
Then you don't need the Handles Itm1.click
in your Sub:
Private Sub Itm1_click(ByVal sender As System.Object,ByVal e As System.EventArgs)
'Do stuff
End Sub
Upvotes: 1
Reputation: 457
When you define a dynamically added button it doesn't exist at runtime so you can't set an event handler like that, what you can do is the following:
Dim Itm As New Button
Itm.Name = "Itm" & i
Itm.Height = 62
Itm.Width = 159
Itm.Text = Temp(i, 0).ToUpper
Itm.Left = (F * 165)
Itm.Visible = True
Itm.BackColor = Colour
Itm.ForeColor = Color.Black
AddHandler Itm.Click, AddressOf Me.Itm1_Click
Me.pnlItemButton1.Controls.Add(Itm)
Then set a protected Event Handler:
Protected Sub Itm1_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Upvotes: 1