ASP.net VB.net Dynamically add code behind a button

Hi. I use the following code to add a button dynamically to a web page.
Is it possible to add code behind the button click?

Dim btn As New Button
        btn.Text = "Push me!"
        Panel1.Controls.Add(btn)
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAsked:
Who is Participating?
 
Fernando SotoConnect With a Mentor RetiredCommented:
Hi,

This line of code adds the handler.

AddHandler btn.Click, AddressOf HandlerName

Where HandlerName is the name of the Sub which handles the Click event.
0
 
Fernando SotoRetiredCommented:
Hi murbro;

This should give you what you need. Use the AddHandler to add a click event handler to btn and give it the address of the event handler you want to give to the btn object as shown below.

Dim btn As New Button
btn.Text = "Push me!"
AddHandler btn.Click, AddressOf HandlerName
Panel1.Controls.Add(btn)

' Event handler needs the correct signature for a button click event
Private Sub HandlerName(sender As Object, e As System.EventArgs)

' Handler code goes here

End Sub

Open in new window

0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Hi. Thanks. What code would I use to add the handler
0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Thanks  very much
0
 
Fernando SotoRetiredCommented:
Not a problem, glad to help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.