简体   繁体   中英

Dynamic button click event created OnPreRender doesn't fire

I am creating a button dynamically in the PreRender event like this:

Button myButton = new Button();
myButton.Text = "Test";
myButton.Click += new EventHandler(myButton_Click);
myDiv.Controls.Add(myButton);

This button is render in the browser, but when I click the button, the click event doesn't fire. I tried to create an identical button in the PageLoad event and it works perfectly, but I must create this button it the PreRender event, since creating this dynamic button or not depends on a value which I get only in this event. What can I do so when I click a dynamic button created in the PreRender , the click event fires?

You should add your button to the page in the page's OnInit event and wire up it's click event during or before OnLoad and then you can enable/disable your button or make visible/invisible your button using the variable that you will have during the PreRender event. See Joel Coehoorn's answer to this question for more details. Otherwise try using a PlaceHolder control though that may end up being trickier.

protected override void OnInit (EventArgs e)
{
  Button myButton = new Button();
  myButton.Text = "Test";
  myButton.Click += new EventHandler(myButton_Click);
  myDiv.Controls.Add(myButton);

  base.OnInit(e);
}

protected override void OnPreRender(EventArgs e)
{
  myButton.Visible = myConditional;

  base.OnPreRender(e);
}

You should add the button on the preinit phase, otherwhise it won't fire

Asp net lifecycle

Use this event for the following (PREINIT):

  • Create or re-create dynamic controls.

也许在PreRender创建按钮并在PageLoad绑定click事件?

In PreRender you can create some var, which will tell you, that you need create button. And on Render create that button by hand with need JavaScript or with sending form. But you can't use such simple syntax as +=EventHandler, more code need.

According to this link from MSDN, you must add button and event related to it if needed durign the OnInit() as explained here : MSDN Lifecycle

"Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page. Use this event to read or initialize control properties."

To do so, try something like that :

protected override void OnInit(EventArgs e)
{
   // Do some stuff here
   base.OnInit(e);
}

You should move control creation earlier in the page lifecycle. Control events are fired after Load and before PreRender so OnLoad or anything earlier should do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM