How to handle dynamically created buttons in ASP.NET
This problem is very often discussed in Newsgroups:
How can I handle clicks on dynamically created buttons?
Ususally you're adviced to declare the buttons in the CodeBehind of your aspx-Page. But this is not the way to create buttons (or other controls) dynamically, because there is no real dynamic in the process.
If you create buttons on-the-fly, you do not have the possiblity to use their eventhandlers. Take a look at the following codesnippet:
Dim objButton As New Button
objButton.Text = "Click me!"
Page.Controls.Add(objButton)
Once you added the button to your page, you don't have a chance to react on the click.
Really?
What, if there was a chance to react on the button's click? Even if this reaction was not handled by the button's eventhandler? Look at this:
' Registering a hidden field in the Page
Page.RegisterHiddenField(Me.UniqueID & _
"_buttonClicked", "")
' Defining the Button
Dim objButton As New Button
objButton.Text = "Click me!"
' Here's the trick... :)
objButton.Attributes.Add("onClick", _
"document.forms[0]." & Me.UniqueID & _
"_buttonClicked.value='" & _
objButton.UniqueID & "';document.forms[0].submit();")
' Adding the button to the page
Page.Controls.Add(objButton)
What was done here? Really simple: We added a JavaScript to the button which sets a value in the hidden field. On PostBack we're able to track this hidden field and detect, wheter the button was clicked or not:
' Use this snippet on PostBack
If Page.IsPostBack Then
If Request.Item(Me.UniqueID & _
"_buttonClicked").Length > 0 Then
Response.Write("Button " & _
Request.Item(Me.UniqueID & _
"_buttonClicked") & _
" was clicked!")
End If
End If
On this place you can add your own handling of the event or raise another event. In any case: You are able to track, wheter the button was clicked or not. Problem solved. :)