Link to home
Start Free TrialLog in
Avatar of PeterErhard
PeterErhard

asked on

Best way to handle NULLs

What's the best way to deal with NULL values in VB.net? If one of the values I'm receiving from the database is NULL I get "ErrorSystem.InvalidCastException: Cast from type 'DBNULL' to type 'String' is not valid'

   Private Function LoadOrgansation() As Boolean()
        Try

            'Check the status of the connection
            CheckConnectionStatus()

            Dim cmd As SqlCommand = cnn.CreateCommand
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "procLoadOrganisation"

            'Input Parameter
            cmd.Parameters.Add(New SqlParameter("@OrganisationIDAuto", SqlDbType.Int))
            cmd.Parameters("@OrganisationIDAuto").Value = CInt(txt_ServiceProvider.Tag)

            Dim reader As SqlDataReader = cmd.ExecuteReader
            If reader.Read Then
                With reader
                    txt_OrganisationName.Text = CType(.GetValue(.GetOrdinal("ProviderName")), String)
                    txt_PostalAddress.Text = CType(.GetValue(.GetOrdinal("Address")), String)
                    txt_PostalCity.Text = CType(.GetValue(.GetOrdinal("City")), String)
                    txt_Phone.Text = CType(.GetValue(.GetOrdinal("Phone")), String)
                    txt_Email.Text = CType(.GetValue(.GetOrdinal("EMail")), String)
                    txt_ContactPerson.Text = CType(.GetValue(.GetOrdinal("ContactPerson")), String)
                    txt_OrganisationNotes.Text = CType(.GetValue(.GetOrdinal("Description")), String)
                End With
                reader.Close()
            End If

        Catch ex As Exception
            MessageBox.Show("ERROR" & ex.ToString)
        Finally
            cnn.Close()
        End Try
    End Function
ASKER CERTIFIED SOLUTION
Avatar of ndonhauser
ndonhauser

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of iboutchkine
iboutchkine

check value for null before writing to textbox

if value is System.DBNUll.Value then
  txt.text = ""
else
  txt= CType(.GetValue(.GetOrdinal("Phone")), String)
end if

keep in mind that you also can do it in TryCatch blok. But the first approach is faster
Avatar of PeterErhard

ASKER

Thanks ndonhauser - your solution seems the most logical :)