Dynamically added ASP.NET mouse click handler ignored

I add event handlers to this button:

btn.Click += new EventHandler(btn_Click); 

However, the btn_Click function btn_Click not called (it never hits a breakpoint in it), and the button simply reloads the page. In my past experience, asp buttons usually execute click code before reloading the page, so how can I get this to happen when the event is dynamically added?

I also set CausesValidation = false , although there is no confirmation on the page, so I donโ€™t think that would affect everything.

+1
source share
2 answers

An event handler must be bound for each request, regardless of whether the page is sent back. The event handler binding is lost at the beginning of each page request. Event handlers for buttons are usually linked in Page_Load.

+2
source

You must install event handlers on the Load event (or earlier). If you do this after Load , it will not be executed, because by the time the handler for the event is evaluated, it will not be there.

Mark this msdn article regarding the page life cycle. I think this will help you understand. See what event processing happens after Load

+1
source

All Articles