Reputation: 1838
I have a problem. While I am adding an event handler from code behind to a button the event never gets fired. But when I add it from when creating the button tag it works perfectly and I am creating the button from code behind and I adding it to table.
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="show table" OnClick="Button1_OnClick" />
<table border="1">
<thead>
<tr>
</tr>
</thead>
<tbody id="tbody" runat="server">
</tbody>
</table>
</div>
</form>
protected void Button1_OnClick(object sender, EventArgs e)
{
var row = new TableRow();
var btnDownload = new Button { ID = "ID", Text = "Click Here" };
btnDownload.Click += ClickEvent;
var cell = new TableCell();
cell.Controls.Add(btnDownload);
row.Controls.Add(cell);
tbody.Controls.Add(row);
}
protected void ClickEvent(object sender, EventArgs e)
{
Debug.WriteLine(((Button)sender).Text);
}
Upvotes: 3
Views: 11560
Reputation: 3107
Please don't accept this as the answer, chappoo answered your question.
Since an event is fired one time, your control will exist just once and will disappear on next PostBack
. You shouldn't create/delete controls in a PostBack
event. Dynamic server controls must be created during the Init
of the page.
Here are some links to understand ASP.NET and ASP.NET MVC 'life cycles'.
ASP.NET
You can see that any controls must exist during the Load
of the page to raise the control events (RaiseChangedEvents
) and post back events (RaisePostBackEvent
). For example, page child controls -and controls sub-controls- are created (CreateChildControls
), data-binded (after OnPreRender
) and rendered (RenderControl
) AFTER the page Load
. Sometimes, some developers call the EnsureChildControls
in the page Load
to pre-load the child controls.
http://msdn.microsoft.com/en-us/library/ms178472.aspx
ASP.NET MVC
'Life cycle' is purely for request processing. Actions (Controller) are rendering (View) independent.
ASP.Net MVC - Request Life Cycle
Upvotes: 8
Reputation: 3081
The answer to this question lies in understanding the ASP.NET page lifecycle. ASP.NET reconstructs a server instance of the page on postback. Once the server is done processing and the response is sent back to the client, the server instance is destroyed forever, and can only be recreated using a combination of the data contained in the browser (view data / cookies etc) and remaining server data (session / cache).
You're wiring up the click event of the dynamic button in the Button1_OnClick event handler. When ASP.NET tries to reconstruct the page on the next postback, it will not run this event handler (as Button1 wasn't clicked) so the event handler will never be wired up, explaining why it never runs. You need to wire any event handlers in or before the Page_Load handler in order to capture control event handlers.
Upvotes: 5