Groups | Blog | Home
all groups > asp.net building controls > august 2004 >

asp.net building controls : How to add an event handler at run time?


Jeff
8/24/2004 10:25:04 AM
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
Jeff
8/24/2004 2:57:07 PM
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;
}
Mark Fitzpatrick
8/24/2004 4:27:06 PM
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


[quoted text, click to view]

Ben Lovell
8/26/2004 9:44:59 PM
In which event are you adding your array of buttons to your page's controls
collection?

--
Ben
http://bitarray.co.uk/ben


[quoted text, click to view]

Niranjan
9/15/2004 3:45:52 PM
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
[quoted text, click to view]

AddThis Social Bookmark Button