Thursday, September 27, 2007

Properties In User Controls - A Tip And Trick

Introduction


I am writing this article to share with you a special tip and trick to persist the property values in user controls during postbacks.

Wrong Approach



private String myName;

public String MyName
{
get{return myName;}
set{myName = value;}
}


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

Right Approach



public String MyName
{
get
{
Object o = ViewState["MyName"];
if(o == null)
{
return null;
}
else
{
return (String)o;
}
}
set
{
ViewState["MyName"] = value;
}
}


This right approach persists your property values during postbacks.

Summary


This concludes that whenever you want to use properties in your controls, it is the best approach to use ViewState with your properties. Which will always persist you Property Values.

No comments: