How to handle Dynamic Controls within User Controls

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
 
F

Felbrigg

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
 
M

Michael Ramey

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top