In this article I will explain with an example, how to preserve state and values of custom properties across PostBacks in ASP.Net using C# and VB.Net.
Why it is important to preserve?
In programming, we often make use of custom properties to pass data from page to Web User Control and vice versa in ASP.Net.
Example
Below is an example of normal property of a Web User Control.
If you use the below properties and set its value only once inside the condition of Not IsPostback, then it will lose its value whenever PostBack occurs.
C#
private string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
}
}
VB.Net
Private _message As String
Public Property Message() As String
Get
Return _message
End Get
Set(ByVal value As String)
_message = value
End Set
End Property
Solution
In order to get rid of this problem, we need to modify the property and preserve its state across PostBacks using ViewState.
This is due to the fact that I have replaced the private (Access Modifier) intermediate variable with ViewState variable.
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
To make it more efficient and elegant and to avoid NULL object reference exceptions, you can modify the property in the following way.
Example
In the above property I have added NULL check for ViewState object and if the ViewState object is NULL default value is returned.
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