How to add an event handler at run time?

J

Jeff

I have created an array of buttons at run time and need to associate them a
click event. I have added the following routine as the event:

public void UpdateClick(Object sender, EventArgs e)
{
lblError.Visible=true;
lblError.Text="It worked";
}

Below I have included the line of code used to hook up the button with the
event:

btnUpdate[intElement1].Click+=new System.EventHandler(UpdateClick);

The code in the click routine does not run when the button is clicked. Can
anyone tell me what I am missing? Thanks in advance.

Regards,
Jeff
 
M

Mark Fitzpatrick

Best bet is to make sure that the click events are wired up before they are
added to the page's control array. This is usually the problem I've run
into, trying to change it after it's been added to the page.

Hope this helps,
Mark Fitzpatrick
Microsoft MVP - FrontPage
 
J

Jeff

I tried Mark's suggestion by placing my addhandler code before the code that
adds the control to the control collection, but it still isn't working. Any
other suggestions? I have included more of the relevant code below. The code
builds the runtime created button array.

//create array of Update buttons
intLeft=16;
intTop=600;
for(intElement1=0;intElement1<datResults.Tables[0].Rows.Count;intElement1++)
{
btnUpdate[intElement1]=new Button();
btnUpdate[intElement1].Style["Position"]="Absolute";
btnUpdate[intElement1].Style["Top"]=System.Convert.ToString(intTop) +
"px";
btnUpdate[intElement1].Style["Left"]=System.Convert.ToString(intLeft) +
"px";
btnUpdate[intElement1].Text="Update";
btnUpdate[intElement1].Height=21;
btnUpdate[intElement1].Width=60;
btnUpdate[intElement1].Click+=new System.EventHandler(this.UpdateClick);
this.FindControl("WebForm1").Controls.Add(btnUpdate[intElement1]);
btnUpdate[intElement1].Visible=true;
intTop+=106;
}
 
B

Ben Lovell

In which event are you adding your array of buttons to your page's controls
collection?
 
N

Niranjan

Jeff,

I guess you are adding the handler for the click event in the
"Page_PreRender" as by this time all the controls are created ready to be
rendered. I hope this helps.

Regards,
Niranjan
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top