specified cast is not valid

[亡魂溺海] 提交于 2019-12-25 16:51:44

问题


Here is a code that retrieve values from the database, but my problem is that it throws out an exception saying "InvalidCastException was unhandled specified cast is not valid". I am now confused what went wrong, The code and the table stated below.

Here is the code:

Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" & Application.StartupPath & 
                "\TestData.accdb; Persist Security info = false"
Public Conn As New OleDbConnection

Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loard
    Conn.ConnectionString = connstring
    Conn.Open()

    LoadValue( )

End Sub 

Private Sub LoadValue( )
    Dim i As Integer    
    Dim cmd As OleDbCommand = New OleDbCommand

    With cmd
        .CommandText = "SELECT MAX(Guard_ID) FROM Guard"
        .CommandType = CommandType.Text
        .Connection = Conn
        .ExecuteNonQuery()

        Dim reader As OleDbDataReader = cmd.ExecuteReader


        If reader.Read Then

            TextBox1.Text = reader.GetString(0)
        i = TextBox1.Text + 1
        TextBox1.Text = i

            reader.Close()
        End If
    End With

End Sub 

The table reference:

Exception Error:

I am really confused now on why the code does not work, any help and advice will be gladly accepted. Thanks in advance.


回答1:


try this,

Private Sub LoadValue()
    Dim i As Integer
    Dim cmd As OleDbCommand = New OleDbCommand

    With cmd
        .CommandText = "SELECT MAX(Guard_ID) FROM Guard"
        .CommandType = CommandType.Text
        .Connection = Conn
        .ExecuteNonQuery()

        Dim reader As OleDbDataReader = cmd.ExecuteReader


        If reader.Read Then

            Dim tmpVal As Object = reader.Item(0)
            TextBox1.Text = IIf(IsDBNull(tmpVal), "0", tmpVal.ToString())

            i = CInt(TextBox1.Text) + 1
            TextBox1.Text = i.ToString()

            reader.Close()
        End If
    End With

End Sub


来源:https://stackoverflow.com/questions/23821115/specified-cast-is-not-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!