Registering onclick of a programatically created button

C

CyberMan_(MCDST!)

Hi,
I programmatically create a/some buttons:

private TableCell GenerateButtonInCell(XmlNode NodeItem)
{
Button ChoosePlanButton = new Button();
ChoosePlanButton.CommandArgument = NodeItem.OuterXml;
ChoosePlanButton.UseSubmitBehavior = false;
ChoosePlanButton.ToolTip = "Request this plan";
ChoosePlanButton.Text = String.Concat("Apply");
TableCell InnerTableCell = new TableCell();
InnerTableCell.Controls.Add(ChoosePlanButton);
return InnerTableCell;
}


I attach it/them all to the same handler:

void ChoosePlanButton_Click(object sender, EventArgs e)
{
//PERSIST THE CHOSEN PLANS ATTRIBUTES TO VIEWSTATE
Button temp = (Button)sender;
ViewState.Add("ChosenPlan", temp.CommandArgument);

}

then I try to register them pre page render thus:

override protected void OnInit(EventArgs e)
{

if (ChoosePlanButton != null)
{ ChoosePlanButton.Click += new
EventHandler(ChoosePlanButton_Click); }

base.OnInit(e);

}

but obviously I cant reference the ChoosePlanButton instance outside the
method.

How do accomplish this?

Many thanks.
 
M

Misbah Arefin

you could simply register the event/handler in your GenerateButtonInCell
function
 
C

CyberMan_(MCDST)_nuub

I tried that, it doesnt get called...

Perhaps I am missing something obvious???

I will try it again.
 
S

Scott Roberts

You will need to ensure that the dynamic button(s) and click event
handler(s) are re-created *before* the event processing stage of the page
lifecycle. I believe that the recommended event it Page_PreInit.

http://msdn2.microsoft.com/en-us/library/ms178472.aspx

Note that although it may not be completely intuitive (to me, at least) you
must "re-hook" the event handler on postback in order for it to fire.
 

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,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top