0
votes

I have a page that has 5 user controls of the same typ. Each user control has a gridview and a couple of buttons.

I don't understand why the controls on the user controls don't retain their value.

EDIT

Below is how I'm populating the gridview inside a user control.

    protected void Page_Load(object sender, EventArgs e)
    {
        var list = new List<CKListByDprtment>
        {
            new CKListByDprtment { ID = 1, TaskName = "New laptop needed", 
            CompletedBy = "My Boss", HMReq = true },
            new CKListByDprtment { ID = 2, TaskName = "New Workstation needed",
            CompletedBy = "My Boss", HMReq = false }
        };

        gvCKList.DataSource = list;
        gvCKList.DataBind();        

    }
    #endregion

    #region GridView Validation
    protected void cvValidateGrid_ServerValidate(object sender, ServerValidateEventArgs args)
    {
        ValidateGrid();
    }

    private void ValidateGrid()
    {
        foreach (GridViewRow gvRow in gvCKList.Rows)
        {
            CheckBox ckHMreq = gvRow.Cells[0].FindControl("ckHMreq") as CheckBox;
        }
    }

I tried to add a checkbox on the main aspx page. When the page posted back, the checked was able to retain its value. I tried also on the user control but not inside the gridview. When the postback, the checkbox retained its value.

It looks like only inside the gridview where controls lose their values after a postback. I have added ViewStateMode = "Enabled" first on the aspx page, then on the usercontrol and finaly on the gridview itself, but with no success.

Any reason?

1
Are you adding the user controls dynamically in the code-behind or are they present in the aspx page?Shai Cohen
They are present in the aspx pageRichard77
Where in the page lifecycle are you populating the user controls? I am wondering if the viewstate is restored but maybe you are repopulating the data and it gets overwritten. Do you have if(!Page.IsPostBack) around the usercontrol population code?Shai Cohen
No. I'm still building the pages. So I'm more focused on the validation (as you van see). There's just some lines of code to populate the gridview. See the EDIT for the code I'm using in the back.Richard77
From the accepted answer, I guess I was right? :)Shai Cohen

1 Answers

1
votes

It seems to me that for every PostBack you are calling DataBind(). You should only call DataBind() if Page.IsPostBack equals false.