Handling events of dynamically added controls

alemargo

Newcomer
Joined
Jan 2, 2004
Messages
16
Hi,

I have one question. If I dynamically add a image button upon form_load, how do I handle its events?
 
If you're still working on this one - I've spent days trying to figure out the same problem only to find that the answer is horribly simple...

use the AddHandler method after creating your new control to wire an event to a handler exactly the same as you would in garden variety VB .net

eg.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim btnTest As New Button()
btnTest.Text = "Click Me!"
AddHandler btnTest.Click, AddressOf OnButtonClick

PlaceHolder1.Controls.Add(btnTest)

End Sub

Private Sub OnButtonClick(ByVal sender As Object, ByVal e As EventArgs)
Response.Write("Button Clicked")
End Sub

if you need to create more than one button and handle each separately, you can set the CommandName or Command Argument properties of the button when you create it and then check for it in the handler

If ctype(sender, button).CommandArgument = "blah" etc
 
Hi guys. When adding controls to a page dynamically (for instance checkboxes), how do you test the .checked property on postback. I have read that the controls need to be recreated on postback, but when they are the default .checked property it initialized to false, which overrides what the user selected. Can you provide any help?
 
dynamic controls

I used attributes to get data from controls. Here is the example.

Private Sub chkGlue_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkGlue.CheckedChanged
If chkGlue.Checked Then
Me.Attributes.Add("name", "Y")
Me.Attributes.Add("descr", "YES")
Else
Me.Attributes.Remove("name")
Me.Attributes.Remove("descr")
End If
End Sub

Then in my parent form, I read this attributes. It works fine.
 
Pretty cool trick. Actually, the problem I found after doing a google search and registering for about 500 discussion forums was that I was recreating the controls "too late" on postback. When I create them in the page_load event, their values remain intact, without the need to use attributes. Although I like that idea.

Thanks for the help.
 
Back
Top