How to Add CommandEventHandler Dynamically AND CONDITIONALLY!

H

haile

Hello all.

The body of literature in MS-Press and in this Newsgroup provides numerous
examples as to how to add event handlers dynamically by means of delegates,
namely:

private void Page_Load (o,e)
{
...
btn1.Command += new System.EventHandler(btn1_Command);
...
}

However, this does not solve the whole problem. We need a way to add
handlers conditionally. Why? Perhaps buttons are to be added to a dynamic
<asp:table> whose row count is to be determined by some user action (such as
a filter).

Since object_load events fire before the postback handlers that would
register a user action, placing the dynamic handlers in the page_load method
(or any other object load method, for that matter) does not work.

Does anyone know of a way to get a dynamic event handler to work from, say,
a button click event?

SUGGESTION:

One way to work around the problem could be to put the dynamic object
creation in the page_load event, but to make it conditional on a boolean
property, which would be set by the user action:

protected bool bMakeDynamicButton = false;

private void Page_Load (o,e)
{
if (IsPostBack && bMakeDynamicButton)
{
...
btn1.Command += new System.EventHandler(btn1_Command);
...
}
}

protected void btnUserActionButton(o,e)
{
// User has clicked to initiate construction of a dynamic control.
bMakeDynamicButton = true;
// Here's where we have to force a postback to cycle back to the page load!
}

The code above gets us halfway there, because the instruction to create the
dynamic button is set to true, but we need another postback! If there is a
way to make a button force a second postback, this workaround could succeed.

Still, even if this method can be made to work, it is a kludge. A clean
solution would be to have a method of registering a new event handler from
anywhere.

Ideas, anyone?

Happy thanksgiving,
Haile
 
H

haile

Pardon, wrote the above in a rush. Just to be clear,
the delegate in my example would be a WebControls handler, not a System
handler. Correct:

btn1.Command += System.Web.UI.WebControls.CommandEventHandler()

But the problem still stands, and is relevant to both types of delegates.

haile
 

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,053
Latest member
BrodieSola

Latest Threads

Top