1

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.

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
user1442605
  • 192
  • 1
  • 8
  • 2
    Which event do you have that code? – Claudio Redi Jun 28 '12 at 13:33
  • Check this post: http://stackoverflow.com/questions/1775788/asp-net-dynamic-command-button-event-not-firing – Chandu Jun 28 '12 at 13:37
  • You have to add this code in in Page.Load and not in page.IsPostback? Is this the mistake you are making ? – Anand Jun 28 '12 at 13:38
  • OK I think I get it. I was adding it during another button click, but I need to add it during page load instead for it to work...am I understanding correctly? – user1442605 Jun 28 '12 at 13:43

2 Answers2

2

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.

amartin65
  • 62
  • 4
  • 9
1

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

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155