InvalidCastException saying that "Specified cast is not valid."

Catherine Takishima picture Catherine Takishima · Sep 11, 2012 · Viewed 17.7k times · Source

Hi I got an InvalidCastException saying that "Specified cast is not valid.". I dont know where is the problem. Does my code has an error?

This is my code:

 Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\patientinfo.accdb"
    Conn.Open()

    '====retrieve values in database=============
    Dim statement As String = " SELECT patient_name,patient_age,date_confinement,type_sickness, type_fluid, bottle_used, drop_rate FROM tblPatientInfo WHERE 1 ORDER BY ID "
    RetrieveInfos(statement)

End Sub
Public Sub RetrieveInfos(ByRef statement As String)
    Dim cmd As OleDbCommand = New OleDbCommand
    With cmd
        .CommandText = statement
        .CommandType = CommandType.Text
        .Connection = Conn
        .ExecuteNonQuery()


        '--read records in access database----------------
        Dim reader As OleDbDataReader = cmd.ExecuteReader


        If reader.Read Then

            lblName.Text = reader.GetString(0)
            lblAge.Text = reader.GetString(1)
            lblDate.Text = reader.GetString(2)
            lblSickness.Text = reader.GetString(3)
            lblFluid.Text = reader.GetString(4)
            lblBottle.Text = reader.GetString(5)
            lbldrops.Text = reader.GetString(6)

            reader.Close()
        End If
    End With
End Sub

Any help would be appreciated. Thanks! :3

Answer

Jonathan Nicol picture Jonathan Nicol · Aug 18, 2014

A very annoying part of VB working with datatypes is that some of them cause it to have a huge flap if they're empty. Best way around is to convert the ready to either an empty value or the default null value for the data type. Try the following:

 lblName.Text = If(reader.isdbnull(0),Nothing,reader.GetString(0))
 lblAge.Text = If(reader.isdbnull(1), 0, reader.GetInt16(1))
 lblDate.Text = If(reader.isdbnull(2), date.minvalue, reader.Getdatetime(2)
 lblSickness.Text = If(reader.isdbnull(3), Nothing, reader.GetString(3)
 lblFluid.Text = If(reader.isdbnull(4), Nothing, reader.GetString(4))
 lblBottle.Text = If(reader.isdbnull(5), Nothing, reader.GetString(5))
 lbldrops.Text = If(reader.isdbnull(6), Nothing, reader.GetString(6))