In day to day life in programming we make use of Properties to pass data from Page to Web User Control and vice versa in asp.net. Thus on many occasions we need to preserve the state and values of such properties across PostBack.
Thus in this article I’ll explain how we can actually preserve the Properties by making use of ViewStates
Below is a normal property of a Web User Control
C#
private string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
}
}
VB.Net
Dim _message As String
Public Property Message() As String
Get
Return _message
End Get
Set(ByVal value As String)
_message = value
End Set
End Property
If you use the above properties and set its values only once in Not IsPostback then it will lose its value whenever PostBack occurs.
Thus to avoid we will need to modify the property in the following way
C#
public string Message
{
get
{
return ViewState["Message"].ToString();
}
set
{
ViewState["Message"] = value;
}
}
VB.Net
Public Property Message() As String
Get
Return ViewState("Message").ToString()
End Get
Set(ByVal value As String)
ViewState("Message") = value
End Set
End Property
Now the above property will preserve its state across PostBack unless it is reset. This is due the fact that I have replaced the private intermediate variable with ViewState variable.
To make it more elegant and to avoid any NULL object reference exception you can modify the property in the following way
C#
public string Message
{
get
{
return ViewState["Message"] != null ? ViewState["Message"].ToString() : string.Empty;
}
set
{
ViewState["Message"] = value;
}
}
VB.Net
Public Property Message() As String
Get
Return IIf(ViewState("Message") IsNot Nothing, ViewState("Message").ToString(), String.Empty)
End Get
Set(ByVal value As String)
ViewState("Message") = value
End Set
End Property
In the above property I have added NULL check for ViewState object and if the ViewState object is NULL default value is returned.
With this we come to an end of this article. Hope you liked the same.