ViewState not reatining value on postback / In which stage of page lifecycle is viewstate to be used

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

Question

I apologize in advance if the Title seems absurd. I am trying to understand the answer to both in a situation I am stuck in. I am creating user controls dynamically on a button click while keeping track of the count in viewstate. Following is the code:

private int custControlCountID;

    public int CustControlCountID
    {
        get 
        {
            return (int)(ViewState["CustControlCountID"] == null? 1 : ViewState["CustControlCountID"]); 
        }
        set 
        {
            ViewState["CustControlCountID"] = value; 
        }
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        for (int i = 0; i < CustControlCountID; i++)
        {
            RejRow customControl = (RejRow )LoadControl("~/RejRow .ascx");
            customControl.ID = "rejRow" + i;
            divHolder.Controls.Add(customControl);
        }
    }

    protected void btnNewRow_Click(object sender, EventArgs e)
    {
        CustControlCountID = CustControlCountID + 1;
        RejRow customControl = (RejRow)LoadControl("~/RejRow.ascx");
        customControl.ID = "rejectRow" + CustControlCountID;
        divHolder.Controls.Add(customControl);
    }

I have shared only relevant code. On clicking the button control is added successfully but only once. This is because CustControlCountID is always set to 1 on Page_Init. I have learnt that LoadViewState is called after Page_Init hence the value I am setting is not available in Page_Init. I have also learnt that controls to be added in Page_Init during which control hierarchy is built. Please help me understand this.

Was it helpful?

Solution

A theory suggests that as the ViewState is loaded between Page_init and Page_load, the value you get during Page_init is not from a loaded viewstate, and if you set it, it is probably going to be overridden when the framework actually loads it in the following step on the page life cycle.

You could try loading your controls initially by overriding the CreateChildControls method.

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