In this article I will explain how to preserve or persists data / class objects / variable values across PostBacks in ASP.Net.
This is done by saving the data / class objects / variable in a ViewState object and then fetching it from it whenever needed.
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.
In similar way you can store anything in ViewState variable including Custom Class Objects. But in order to store a class object you need to first mark it as Serializable using the [Serializable] attribute.