ASP.NET Wrapper - Preventing Value cannot be null exception

From Visual WebGui Wiki

Jump to: navigation, search

Contents

Overview

In C# and VB.NET, value types (like integer, date etc) cannot take the value NULL. If this occurs either runtime or designtime, the 'Value cannot be null' exception is thrown.

Details

To prevent this exception, you should wrap your valuetype accesses using a null-safe operations. For this you should define a function like the following in your wrapped control:

C#

public object returnSafeValue<T>(object objValue)
        {
            if (objValue == null)
            {
                return default(T);
            }
 
            return objValue;
        }

VB.NET

Public Function returnSafeValue(Of T)(ByVal objValue As Object) As Object
        If objValue Is Nothing Then
            Return CType(Nothing, T)
        End If
 
        Return objValue
    End Function

To apply it, you need to change the code of your wrapper generated code for all the valuetype property access:

C#

public System.Web.UI.WebControls.Unit WrapperWidth
        {
            get
            {
                return (System.Web.UI.WebControls.Unit)this.returnSafeValue<System.Web.UI.WebControls.Unit>(this.GetProperty("Width"));
            }
            set
            {
                this.SetProperty("Width", value);
            }
        }

VB.NET

Public Property WrapperWidth() As System.Web.UI.WebControls.Unit
	Get
		Return DirectCast(Me.returnSafeValue(Of System.Web.UI.WebControls.Unit)(Me.GetProperty("Width")), System.Web.UI.WebControls.Unit)
	End Get
	Set
		Me.SetProperty("Width", value)
	End Set
End Property


See also

Rererences

Articles

Videos

Code samples

Forum discussons

Other references

Personal tools