Click here to Skip to main content
15,885,910 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I am having a very hard time trying to get Visual Studio to connect to an Access DB upon a button_click event. I have tried everything but always end up with the error: "ExecuteNonQuery: Connection property has not been initialized."

Here is the code:

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.OleDb


Public Class Form1

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Label1.Text = Date.Now
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Dim connStr As String
        connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Tech\LoanerTracking.accdb"

        Dim objConn As New OleDbConnection(connStr)

        'objConn = CreateObject("ADODB.Connection")

        Dim str As String
        str = "insert into [TrackingInfo] ([UserName], [AssetType], [BadgeNumber], [AssetBarcode], [DateNTime]) values (?, ?, ?, ?, ?)"
        Dim cmd As OleDbCommand = New OleDbCommand(str)


        objConn.Open()

        Try
            cmd.Parameters.Add(New OleDbParameter("UserName", CType(Me.Controls("ListBox1").Text, String)))
            cmd.Parameters.Add(New OleDbParameter("AssetType", CType(Me.Controls("ListBox2").Text, String)))
            cmd.Parameters.Add(New OleDbParameter("BadgeNumber", CType(Me.Controls("TextBox1").Text, String)))
            cmd.Parameters.Add(New OleDbParameter("AssetBarcode", CType(Me.Controls("TextBox2").Text, String)))
            'cmd.Parameters.Add(New OleDbParameter("CheckedOut", Text = 1))
            cmd.Parameters.Add(New OleDbParameter("DateNTime", CType(Me.Controls("Label1").Text, String)))
            cmd.ExecuteNonQuery()
            cmd.Dispose()
            objConn.Close()

            MsgBox("Records Inserted Successfully")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

End Class


What I have tried:

I have tried changing the connection parameters around by defining them under the DIM as well as trying to string them together by using multi-defined variables.
Posted
Updated 5-Jun-17 6:19am

1 solution

It is the command you are executing but where are you telling it to use the connection defined by objConn? How does the command know what database to execute against? You need to tell the command which connection to use

Dim cmd As OleDbCommand = New OleDbCommand(str)
cmd.Connection = objConn
objConn.Open()
 
Share this answer
 
Comments
KD209 5-Jun-17 12:26pm    
That did the trick. Thank you, I do not know how I overlook setting the command!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900