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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With