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.InvalidCastEx ception: 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.StoredProcedur e
cmd.CommandText = "procLoadOrganisation"
'Input Parameter
cmd.Parameters.Add(New SqlParameter("@Organisatio nIDAuto", SqlDbType.Int))
cmd.Parameters("@Organisat ionIDAuto" ).Value = CInt(txt_ServiceProvider.T ag)
Dim reader As SqlDataReader = cmd.ExecuteReader
If reader.Read Then
With reader
txt_OrganisationName.Text = CType(.GetValue(.GetOrdina l("Provide rName")), String)
txt_PostalAddress.Text = CType(.GetValue(.GetOrdina l("Address ")), String)
txt_PostalCity.Text = CType(.GetValue(.GetOrdina l("City")) , String)
txt_Phone.Text = CType(.GetValue(.GetOrdina l("Phone") ), String)
txt_Email.Text = CType(.GetValue(.GetOrdina l("EMail") ), String)
txt_ContactPerson.Text = CType(.GetValue(.GetOrdina l("Contact Person")), String)
txt_OrganisationNotes.Text = CType(.GetValue(.GetOrdina l("Descrip tion")), String)
End With
reader.Close()
End If
Catch ex As Exception
MessageBox.Show("ERROR" & ex.ToString)
Finally
cnn.Close()
End Try
End Function
Private Function LoadOrgansation() As Boolean()
Try
'Check the status of the connection
CheckConnectionStatus()
Dim cmd As SqlCommand = cnn.CreateCommand
cmd.CommandType = CommandType.StoredProcedur
cmd.CommandText = "procLoadOrganisation"
'Input Parameter
cmd.Parameters.Add(New SqlParameter("@Organisatio
cmd.Parameters("@Organisat
Dim reader As SqlDataReader = cmd.ExecuteReader
If reader.Read Then
With reader
txt_OrganisationName.Text = CType(.GetValue(.GetOrdina
txt_PostalAddress.Text = CType(.GetValue(.GetOrdina
txt_PostalCity.Text = CType(.GetValue(.GetOrdina
txt_Phone.Text = CType(.GetValue(.GetOrdina
txt_Email.Text = CType(.GetValue(.GetOrdina
txt_ContactPerson.Text = CType(.GetValue(.GetOrdina
txt_OrganisationNotes.Text
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks ndonhauser - your solution seems the most logical :)
if value is System.DBNUll.Value then
txt.text = ""
else
txt= CType(.GetValue(.GetOrdina
end if
keep in mind that you also can do it in TryCatch blok. But the first approach is faster