How to handle Dynamic Controls within User Controls

  • Thread starter Thread starter Michael Ramey
  • Start date Start date
M

Michael Ramey

Howdy, I think I have a good question!

I'm creating a usercontrol, and within this usercontrol, I'm dynamically
creating controls (imagebuttons to be exact), that the user can click on
which will cause a postback to occur.

My problem is, I can't seem to be able to get the handlers to work within
the user control, to determine which control has been clicked, and what to
do with it from there.

I want these events to be handled within the user control itself, and not
the page that has the user control.

Here is what I've been doing:

'I'm adding this imagebutton to a tablecell I'm dynamically creating as
well, for simplicity i'm not showing that this code is part of a for each
loop, and it can be ran many times...

Dim dImage as ImageButton = new ImageButton

AddHandler dImage.click, AddressOf DeleteButton_Click
dImage.imageurl = "../images/delete.gif"
dImage.tooltip = "Delete this Item"
tblcellDelete.Controls.Add(dImage) 'tcDelete is a TableCell
tblRow.Controls.Add(tcDelete) 'trow is a TableRow
tblShow.Controls.Add(trow) 'tblShow is a Table

Then I create the event handler in the user control

Sub DeleteButton_Click(ByVal sender As Object, ByVal e As
System.Web.UI.ImageClickEventArgs)
Response.Write("clicked an image?")
End Sub

For now I'm just using Response.write with a breakpoint on that line to see
if that code executes. Unfortunately the DeleteButton_Click Sub is never
called, the page just posts back. Can someone tell me the proper way to
handle events for dynamically created controls within user controls?

Thanks!
--Michael
 
I've done a similar thing myself, emphasis on SIMILAR.
I fix my similar problem I had to reload all of the dynamic controls on each
postback, the viewstate info then allowed the events to take place.

Hope that helps
 
Worked great, just one thing, the button i'm writing the event for is a
"delete" button, so on a postback, I wouldn't want it to appear again. I
suppose I can search and delete the control before it is rendered again.
Thanks for the info, it did help.
 
Back
Top