How to store object in ViewState?

We can store objects in viewstate like we store string or integer. But before storing we need to convert them into stream of bytes to keep tem in hidden field. So we need to use Serialization. And object which can’t be serialised, they will not be able to keep in viewstate.

[Serializable]
public class Student
{
public int Roll;
public string Name;
public void AddStudent(int intRoll, string strName)
{
this.Roll = intRoll;
this.Name = strName;
}
}

Now we need to store them to viewstate.

Student _objStudent = new Student();
_objStudent.AddStudent(2, "Max");
ViewState["StudentObj"] = _objStudent;

//Retrieving student
Student _objStudent;
_objStudent = (Student)ViewState["StudentObj"];
Advertisements

Leave a comment

Filed under ASP.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s