August 10, 2005

Viewstate & object serialization

Recently i came across a problem which i cant put a object into viewstate. So i did some research on that & found, if we want to put a object into viewstate we have to make the class serializable by adding serializable attribute. Then you can put your object into the view state. code below.

[Serializable]
public class User
{
public User()
{
//
// TODO: Add constructor logic here
//
}

string _name;
string _age;
string _address;

public string Name{get{ return _name;}set{_name = value;}}
public string Age{get{ return _age;}set{_age = value;}}
public string Address{get{ return _address;}set{_address = value;}}

}

//In the web form page

private void Page_Load(object sender, System.EventArgs e)
{
user = new User();
user.Name = "Ludmal";
user.Age = "25";

}

private void Button2_Click(object sender, System.EventArgs e)
{

ViewState["User"] = user;
}

private void Button1_Click(object sender, System.EventArgs e)
{
user = (User)ViewState["User"];
Response.Write("My Name is " + user.Name);
}

No comments: