none
Visual Basic Error Reading MS Access mdb database

    Question

  • I am getting a System invalid cast exception when trying to read one of my MS Access mdb fields into a VB.Net 15 TextBox.  The field in the MS Access database is defined as text with a field size of 4.  The particular exception occurs when the field of the first record is attempted to be placed in the textbox.  The particular field contains the text "0005" without the quotes. The error I get is "System.InvalidCastException  {Unable to cast object of type 'System.String' to type 'System.Windows.Forms.TextBox'."}

    Any help would be greatly appreciated.

    Thanks,

    Fred

    Saturday, March 25, 2017 9:40 PM

Answers

  • Since you did not show any code I will provide a method to do what you asked other than I'm using a newer version of ms-access that does not change how the code works and presents data in a TextBox.

    Imports System.Data.OleDb
    
    Public Class DataOperations
        Private Builder As New OleDbConnectionStringBuilder With
        {
            .Provider = "Microsoft.ACE.OLEDB.12.0",
            .DataSource = IO.Path.Combine(Application.StartupPath, "Database1.accdb")
        }
        Public Property DataTable As DataTable
        Public Sub LoadCustomerData()
            DataTable = New DataTable
    
            Using cn As New OleDbConnection With
                {
                    .ConnectionString = Builder.ConnectionString
                }
                Using cmd As New OleDbCommand With {.Connection = cn}
                    cmd.CommandText = "SELECT Table2.id, Table2.SomeField FROM Table2;"
                    cn.Open()
                    DataTable.Load(cmd.ExecuteReader)
    
                End Using
            End Using
        End Sub
    End Class
    
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim ops As New DataOperations
            ops.LoadCustomerData()
            Dim dt As DataTable = ops.DataTable
            TextBox1.Text = dt.Rows(0).Field(Of String)("SomeField")
        End Sub
    End Class
    



    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by Fred R W 70 Sunday, March 26, 2017 3:11 AM
    Saturday, March 25, 2017 10:33 PM
    Moderator