tags:

views:

38

answers:

2

Several of my overriden Equals methods have started throwing Invalid Cast Exceptions -

Unable to cast object of type 'System.DBNull' to type Common.ResolveUser'.

This occurs when binding List (of T) (where T is of type ResolveUser in this case) to a combo.

Equals Method:

    Public Overrides Function Equals(ByVal obj As Object) As Boolean
        Dim i As ResolveUser = CType(obj, ResolveUser)
        If i.UniqueResolveID = UniqueResolveID Then Return True
    End Function

Combo-box Binding:

 Me.cboPreventativeActionOwner.DataSource = CurrentUser.LoadAllTechniciansAndGreater
 Me.cboPreventativeActionOwner.ValueMember = "ID"
 Me.cboPreventativeActionOwner.DisplayMember = "FullName"

The ValueMember and FullName properties are populated properly for each item in the collection.

This all used to work fine (and has for about 6 months!)

A: 

Changing Equals to:

   Public Overrides Function Equals(ByVal obj As Object) As Boolean
        If Not obj Is DBNull.Value And Not obj Is Nothing Then
            Dim i As ResolveUser = CType(obj, ResolveUser)
            If i.UniqueResolveID = UniqueResolveID Then Return True
        End If
    End Function

Seems to fix the problem. Never needed this before though....

Simon
+4  A: 

It sounds like, from the exception, that you're pulling data from your database.

In this situation, you must have a record that is set to NULL, which is causing the "obj" parameter to be set to System.DBNull instead of a "Common.ResolveUser" instance. When this happens, the CType fails, throwing an InvalidCastException.

Reed Copsey
Makes sense but some of the fields have always been null!
Simon
Something obviously changed - it may not be the fields, but how you're loading the data, or some other similar issue - but that's the basic issue at hand.
Reed Copsey