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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.)

Method 2

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; }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x