1

嗨,我收到一个 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

4

3 回答 3

1

VB 处理数据类型的一个非常烦人的部分是,如果它们是空的,它们中的一些会导致它有一个巨大的翻动。最好的解决方法是将 ready 转换为空值或数据类型的默认 null 值。尝试以下操作:

 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))
于 2014-08-18T16:11:41.550 回答
0

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

lblAge.Text = reader.GetString(1)

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

此外,请确保Get为每列使用适当的。对于日期,您应该使用GetDateTime(). 这是 MSDN 的链接OleDbDataReader;左侧将列出您可以参考的所有方法。

于 2012-09-11T18:33:54.757 回答
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
于 2012-09-11T18:34:59.450 回答