Question

Is there any way to update the ViewState from a page event (such as a button click) BEFORE the Load event of the page?

I understand that the event handlers only get called after the load events, but is there any way around this?

Was it helpful?

Solution

Due to the life-cycle of an ASP .net page. The only way to pass state to the server that can be accessed OnPageLoad is by using a HiddenField on the page which is updated on the client-side with Javascript.

OTHER TIPS

 protected void Page_Load(object sender, EventArgs e)
    {
        if (ViewState["val"] != null)
        {
            int s = Convert.ToInt32(ViewState["val"]);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ViewState["val"] != null)
        {
            int s = Convert.ToInt32(ViewState["val"]);
            s = s + 5;
            ViewState["val"] = s;
        }
        else
        {
            ViewState["val"] = 6;
        }
    }

This is the code i tested on my machine and on page load i am getting the updaetd value each time,

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