InvalidCastException表示“指定的强制转换无效”。

时间:2012-09-11 18:20:51

标签: vb.net oledb oledbexception

您好我有一个InvalidCastException,说“指定的演员表无效。”。我不知道问题出在哪里。我的代码有错误吗?

这是我的代码:

 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

任何帮助将不胜感激。谢谢! :3

3 个答案:

答案 0 :(得分:1)

使用数据类型的VB中一个非常讨厌的部分是,如果它们是空的,它们中的一些会导致它有一个巨大的翻盖。最好的方法是将ready转换为空值或数据类型的默认空值。请尝试以下方法:

 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))

答案 1 :(得分:0)

根据您对该问题的评论,我建议您更改

lblAge.Text = reader.GetString(1)

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

另外,请确保为每列使用适当的Get。对于日期,您应该使用GetDateTime()OleDbDataReader的{​​{3}};左侧将列出您可以用作参考的所有方法。

答案 2 :(得分:0)

尝试检查值是否为空:

If TypeOf reader(1) Is DBNull Then
    lblAge.Text = reader.GetString(1)
End If

但只有当它是一个字符串时才会起作用。如果它不是字符串,则应该适用于任何数据类型:

If TypeOf reader(1) Is DBNull Then
    lblAge.Text = reader(1).ToString()
End If