Search code examples
vb.netoledboledbexception

InvalidCastException saying that "Specified cast is not valid."


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


Solution

  • Based on your comment to the question, I would suggest changing

    lblAge.Text = reader.GetString(1)

    to

    lblAge.Text = reader.GetInt32(1).ToString

    Also, make sure you use the appropriate Get for each column. For a Date you should use GetDateTime(). Here is a link to the MSDN for OleDbDataReader; the left side will have a list of all the methods that you can use for reference.