views:

1814

answers:

4

How do I increment a step value to be processed when the page loads? For example, in the code below the viewstate variable is not incremented until after Page_Load, due to the ASP.NET page lifecycle.

protected void Page_Load(object sender, EventArgs e)
{
    switch ((int)ViewState["step"])
    {
        //do something different for each step
    }
}

protected void btnIncrementStep_Click(object sender, EventArgs e)
{
    //when the button is clicked, this does not fire 
    //until after page_load finishes
    ViewState["step"] = (int)ViewState["step"] + 1;
}
+2  A: 

There's no way around this. Page_Load event will always happen before any control events get fired. If you need to do something after the control event, use Page_PreRender.

ASP.Net Page Lifecycle Image

jcollum
A: 

Increment during the LoadComplete event or even during OnLoad.

You have all the information needed to make the decision whether to increment from the form data. You don't need to wait for the onClick() event. Check the form to see if the item will be clicked.

Look in the request.params("__EVENTARGS")

This identifies the control that caused the postback.

Just giving options :)
+1  A: 

Just move the switch statement into an event that happens later. E.g. LoadComplete() or PreRender(). PreRender is probably a bit late, depending on what you want to do.

Robert C. Barth
That will do it. Thanks.
nshaw
A: 

If you need to increment and check the value during Page_Load, then an option would be to store the value in the session instead of ViewState, e.g:

private int Step
{
  get { return (int)Session["step"]; }
  set { Session["step"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
       Step = 0; // init
    else
       Step ++; // increment

    switch (Step)
    {
        //do something different for each step
    }
}
M4N