Search code examples
databasevb.netstringbasic

Why does "Conversion from string "ID" to type integer is not valid" show on my program?


I'm trying to display my database on textboxes, with the help of the combobox for the ID. However, whenever I run my program, the error "Conversion from string "ID" to type integer is not valid" keeps on appearing. What should I do?

Private Sub FormAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    cnn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb")
    Dim reader As OleDb.OleDbDataReader
    Try
        cnn.Open()
        Dim str As String = "select * from TableName"

        command = New OleDb.OleDbCommand(str, cnn)
        reader = command.ExecuteReader
        While reader.Read
            Dim sId = reader.GetName("ID")
            ComboBox1.Items.Add(sId)
        End While
        cnn.Close()

    Catch ex As OleDb.OleDbException
        MessageBox.Show(ex.Message)

    Finally
        cnn.Dispose()

    End Try

End Sub

Visual Basic says that the error is located here:

 Dim sId = reader.GetName("ID")

Thank you so much!


Solution

  • The GetName() function takes an ordinal (integer) representing the column number from the result set. see here. You are passing in a string, hence the error. You want to call the GetValue() function with the column number instead.