On the same Page When I click Save_button, firstly Page_Load event should execute or btnSave_Click button?

StackOverflow https://stackoverflow.com/questions/22723884

  •  23-06-2023
  •  | 
  •  

Question

In my Asp.Net Web Form, Assuming that, I have Main_page and Save_button that it is on Main_page.

When I click Save_button, firstly Page_Load eventexecute and after this btnSave_Click button execute.

I thought that when I click button firstly and only button might execute.

Is it correct or my program doesn't work correctly ?

Was it helpful?

Solution

It is normal that Page_Load is executed first and event handlers afterwards. So your program behaves as designed.

Excerpt from MSDN on the page lifecycle:

Load

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Postback event handling

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)

If you are interested in details on the lifecycle of an ASP.NET Page, have a look at this link.


Resolution

If you need to perform certain steps in Page_Load (or any other method on your page) only when the page is requested first, you can check the IsPostBack property and thus make your program behave as you describe in your question:

public void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Steps are only run on initial GET, not when request is a PostBack.
    }
}

OTHER TIPS

It is correct that load event fires first then button event handler. If you want to execute code only at first, but not when any postback check IsPostBack property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top