0

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?

1

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

But using that added line, is hard coding Itm1, when the Itm Name is in a loop with Itm & i, so will not always be Itm1?
Every added button will have the same EventHandler, there is no other way in Vb.net to dynamically add an EventHandler to a button besides this, also it isn't hardcoded, the only hardcoded part is your itm1_click
1

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

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.