Tuesday, June 17, 2008

Persist the Property Values in User Controls after postbacks.

private String strName

public String Name
{
get{return strName;}
set{strName= value;}
}

This
is wrong approach,It will lose your property values. whenever
you want to get the value of Name Property it will never get in
postbacks and you will always get the Null Exception.


Right Way

public String Name
{
get
{
Object obj = ViewState["Name"];
if(obj == null)
{
return null;
}
else
{
return (String)obj;
}
}
set
{
ViewState["Name"] = value;
}
}
You will retain property value of user control during postback too.

2 comments:

Anonymous said...

in Set you can always add SaveViewState()

Anonymous said...

SaveViewState() in Set