Hello. I am working on a C#/ASP.NET web application. What I want to accomplish is the following:
1. When a page named "Qwan.aspx" is loaded, then set a global variable "myVar" in the Page_Load method for the code behind page Qwan.cs.
2. Display the web form Qwan.aspx on the screen.
3. A user presses a button on the web page Qwan.aspx.
4. Step 3 causes the button event handler method to be called.
The problem here is that when step 3 is performed, code execution again goes to the page_load method of the Qwan.cs file. Why is this? Shouldn't code execution go directly to my event handler(Method) for the button control?
Your thinking is like WinForms developer, but in ASP.NET it is a little bit different. ASP.NET uses communication in style request - response. Browser creates requests and server sends response. When is request to server send, ASP.NET executes page and also complete page lifecycle. Page_Load method is part of page lifecycle, this method is called at each request. Button event handler is postback event handler, it executes only when button is clicked. Try tu study somethink about ASP.NET page lifecycle and about postback.
thats pretty much what happens. one thing you can do is in your page_load method is add a
//Your code goes here
also i believe you may be interesting in looking up the functionality of the autopostback attribute. i think that might also solve your problem.
Before the code connected to your button can execute, the page must be loaded from disk.
|Stage||Page Event||Overridable method|
|View state loading||LoadViewState|
|Postback data processing||LoadPostData method in any control that implements the IPostBackDataHandler interface|
|Postback change notification||RaisePostDataChangedEvent method in any control that implements the IPostBackDataHandler interface|
|Postback event handling||Any postback event defined by controls||RaisePostBackEvent method in any control that implements the IPostBackEventHandler interface|
|Page pre-rendering phase||PreRender|
|View state saving||SaveViewState|
I pasted the above from this web site:
i recommend you to read the link below which has the best informative information about the page life cycle in order to understand why the page_load event was raised in step 3
Haissam Abdul Malak
| Blog |