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.

4
  • 2
    Which event do you have that code? Commented Jun 28, 2012 at 13:33
  • Check this post: stackoverflow.com/questions/1775788/… Commented Jun 28, 2012 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 ? Commented Jun 28, 2012 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? Commented Jun 28, 2012 at 13:43

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Both of these answers help me to understand, although I can only accept one. Either way, thanks!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.