Asp – Page cycle and viewstate problem

asp.net

Need help with lifecycle of page.

When I have a button it's click handler stores a value in ViewState.
When the button is clicked a postback occurs but when if I try to read the viewstate vale in pageload, I get a wrong value.

When page is refreshed it needs to display a label according to the value in viewstate.

Page_Load is not a right place for that.

In what page event I should display this label?

Best Answer

So the page load events flow as:

  1. Action on form causes Postback
  2. Page_Load Event
  3. Button Click Event
  4. Render/Unload Event

At step 2 you are reading a variable from the viewstate and setting a label. At step 3 you're setting the value in the viewstate.

As you've observed you're using the events in incorrect order. There are two ways you can solve this: Place your label setter code in Render/Unload event. The other is to refactor your code such that the label is set via the Button Click Event instead of in the Page_Load event; which I would recommend as the proper course of action.

You may want to checkout What is the ‘page lifecycle’ of an ASP.NET WebForm? to get a better handle on page lifecycle.


In response to the comment: If there's multiple labels to set you can look at inline code to set your labels. The code would look like this:

CodePage

<asp:Label id="id1" runat="server" text="<%=Label1Text%>" />

CodeBehind

private string m_Label1Text;
public property string Label1Text {
    get { return m_Label1Text; }
    set { m_Label1Text = value; }
}

This way, you set your text via the Label1Text property and it gets transfered to the form when it's rendered. You can try this Tutorial here if you need more information on inlining code.

Related Topic