Reputation: 192
I am adding event handlers to a button like this:
btn.Click += new EventHandler(btn_Click);
However the btn_Click
function is not being called (never hits the breakpoint in it) and the button just reloads the page. In my past experience, asp buttons usually perform the click code before reloading the page, so how do I get that to happen when the event is dynamically added?
I also set CausesValidation = false
, although there's no validation on the page so I don't think that would have influence anyway.
Upvotes: 1
Views: 9532
Reputation: 68400
You have to set event handlers on Load
event (or before). If you do it after Load
, it won't be executed since by the time the handler for the event is evaluated it won't be there.
Check this msdn article in relation to page life cycle. I think it will help you to understand. See that event handling occurs inmediatly after Load
Upvotes: 1
Reputation: 72
The event handler needs to be bound for every request regardless of whether or not the page is being posted back. The binding of the event handler is lost at the start of each page request. Event handlers for buttons are typically bound in Page_Load.
Upvotes: 2