Search code examples
vb.netoledboledbexception

specified cast is not valid


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:

enter image description here

Exception Error:

enter image description here

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


Solution

  • 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