• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1097
  • Last Modified:

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)
0
Murray Brown
Asked:
Murray Brown
  • 3
  • 2
1 Solution
 
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
 
Fernando SotoRetiredCommented:
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
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Thanks  very much
0
 
Fernando SotoRetiredCommented:
Not a problem, glad to help.
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now