Dynamic Controls and their events

M

Michael Ramey

Hello,

I'm trying to handle click events with button controls I've created
dynamically. I've found two ways of dealing with them, neither of which I
like, so I'm asking if anyone knows a better way.

1), register a handler for the click event, as so

Dim btnClick As New Button
btnClick.Text = "Delete"
btnClick.ID = "myButton"
AddHandler btnClick.Click, AddressOf Button_Click()
anotherControl.controls.add(btnClick)

Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim btn As String = CType(sender, Button).ID
myLabel.Text = "The Button " & btn & "was clicked."
End Sub

This works great, but only one "big" problem, I have to rebuild these
controls on postback for the events to fire. Well that does me no good if
on postback, I don't want this control to appear anymore! Lets say I had a
list of items, and my dynamic control was a delete button. If I click this
delete button, I want the item deleted, which would naturally mean the
delete button would need to be gone too.

2), use client side JavaScript, register onClick attributes for each button
to update a hidden field and submit the form, then on postback, retrieve the
hidden fields value, and work accordingly. Much like this example:

http://weblogs.asp.net/ksamaschke/archive/2003/02/18/2595.aspx

This works..ok, but gets a little messy when you have to deal with multiple
events for multiple buttons that all do something different.

Surely there is a better way!, hopefully using something like the first
method, but not needing to rebuild the buttons.

Any help would be appreciated!
--Michael
 

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,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top