Search code examples
c#asp.netpage-lifecycle

ASP.Net Life Cycle And Control State And View State


In msdn , they mentioned as, view state values is loaded between page_init and page_initcomplete. Lets us assume , during the get request I am assigning a value to text property of text box as get with in page_load () { if(!IsPostBack) {textobx.text="get";}} . So this get value is stored in viewstate and visible in browser. And during my next postback I am assigning a post value to same text property in page_init event . So as per msdn , after page_initcomplete event this post value must be override by the get value . But it doesn't happen that way . Why ?

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "hello";
        }
        TextBox2.Text = TextBox1.Text.ToString();

    }
    protected override void OnPreInit(EventArgs e)
    {
            base.OnPreInit(e);
            TextBox1.Text = "init";
    }
    protected override void OnInitComplete(EventArgs e)
    {
            base.OnInitComplete(e);
            TextBox1.Text = "init";

    }

First time the value is hello in Textbox2.Text this is fine . But during post back I am expecting init value on textbox2.text . But it is still hello. why ?


Solution

  • You are not quite correct in your ViewState assumption. As described in ASP.NET Page Life Cycle Overview, the ViewState is loaded AFTER InitComplete.

    Meaning, whatever you write into the control's properties in Init or InitComplete (which btw is not recommended at that point of the Life Cycle) will definetly be overwritte by the ViewState between InitComplete and Load.

    The behaviour your page is showing is correct.