Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to know that how can i store a class into viewstate. can i do or not?
Posted

 
Share this answer
 
v2
Yes . You can store class object in Page view state.

Let assume, we have a class "ABC"

C#
Class ABC
{
   public string a{get;set;}
   public string b{get;set;}

}


Now we want to store this class on view state on page load
C#
protected void Page_Load(object sender, EventArgs e)
       {
           if (!IsPostBack)
           {
          ABC objAbc = new ABC();
           ViewState["CheckPoint"] = objAbc ;
       }
     }


You can access this object on any other event or other function of the page.
C#
protected void Button1_Click(object sender, EventArgs e)
       {
           ABC objAbc = = (ABC)ViewState["CheckPoint"];
       }
 
Share this answer
 
Comments
Vimal Kumar 18-Jun-14 6:54am    
nice thanks
You can keep object of a class in a viewstate, and later you can cast back class object from viewstate into a class object.

C#
SampleClass classObj = new SampleClass();
ViewState["test"] = classObj;
SampleClass obj = (SampleClass)classObj;
 
Share this answer
 
Yes you can store a class in the ViewState, just make sure the class is marked as [Serializable] otherwise you may encounter some errors.

C#
[Serializable]
public class MyClass
{
   public string StringProperty { get; set; }
}


C#
public MyClass myClass
{
   get { return (MyClass)ViewState["MyClass"]; }
   set { ViewState["MyClass]" = value; }
}


Don't forget the cast on the Return of the property.
 
Share this answer
 
v3
Comments
ICTechnology 12-Nov-13 10:52am    
It's quite amusing getting down voted with no explanation as to why.
CHill60 12-Nov-13 10:55am    
i know the feeling. It might be because the original post was over a year old
ICTechnology 12-Nov-13 12:14pm    
I've been down voted on other sites for stranger reasons. Meh, nevermind :)
Yes you can store Id in viewstate, but class viewstate make no sense
By storing Id you can call this only that particular page beacuse the viewstate expires with single page in which if you will use viewstate
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900