Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User control's property loses value after a postback

This is the HTML. I have a repeater that contains a user control.

<asp:Repeater ID="rpNewHire" runat="server">
 <HeaderTemplate>
  <table>            
 </HeaderTemplate>
 <ItemTemplate>
  <tr>
     <td>
         <user:CKListByDeprtment ID = "ucCheckList" 
          DepartmentID= '<%# Eval("DepID")%>' 
          BlockTitle = '<%# Eval("DepName")%>' 
          runat = "server"></user:CKListByDeprtment>
     </td>
   </tr>
  </ItemTemplate>
  <FooterTemplate>
   </table>
  </FooterTemplate>
</asp:Repeater>

DepartmentID is a property that I defined inside the user control.

int departmentID;

public int DepartmentID
{
  get { return departmentID; }
  set { departmentID = value; }
}

And this is how I am trying to access it

protected void Page_Load(object sender, EventArgs e)
{
   int test = departmentID;
}

When the page loads for the first time, departmentID has a value. However, when the page Posts back, that value is always 0.

like image 626
Richard77 Avatar asked Feb 19 '13 14:02

Richard77


2 Answers

All variables (and controls) are disposed at the end of the page's lifecycle. So you need a way to persist your variable, e.g. in the ViewState.

public int DepartmentID
{
    get {
        if (ViewState["departmentID"] == null)
            return int.MinValue;
        else 
            return (int)ViewState["departmentID"]; 
    }
    set { ViewState["departmentID"] = value; }
}

The MSDN Magazine article "Nine Options for Managing Persistent User State in Your ASP.NET Application" is useful, but it's no longer viewable on the MSDN website. It's in the April 2003 edition, which you can download as a Windows Help file (.chm). (Don't forget to bring up the properties and unblock the "this was downloaded from the internet" thing, otherwise you can't view the articles.)

like image 170
Tim Schmelter Avatar answered Nov 18 '22 17:11

Tim Schmelter


Change your property to use viewstate

int departmentID = 0;
public int DepartmentID
{
  get { 
         if(ViewState["departmentID"]!=null)
         { departmentID = Int32.Parse(ViewState["departmentID"]); }; 
         return departmentID;
      }
  set { ViewState["departmentID"] = value; }
}
like image 26
rs. Avatar answered Nov 18 '22 19:11

rs.