I have been struggling with the below code trying to get it to work. I have never used the OleDbDataAdapter & OleDbCommand and am not sure what I am doing. Keep getting this err msg at the high-lighted code, "Object reference not set to an instance of an object". I must have more than one thing wrong. I copied this code from the internet. Also don't know what to put in those ? marks.
I am using Access 2010 and vs2013 express.
Imports System.Data.OleDb
Public Class Form1
Dim myDA As OleDbDataAdapter
Dim myDataSet As DataSet
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=|DataDirectory|\test.mdb") ' Use relative path to database file
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Table1", con)
con.Open()
myDA = New OleDbDataAdapter(cmd)
'Here one CommandBuilder object is required.
myDA.UpdateCommand = New OleDbCommand("UPDATE Table1 SET Field1 = ?, Field2 = ?")
'It will automatically generate DeleteCommand,UpdateCommand and InsertCommand for DataAdapter object
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "Table1")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
End Sub
' Save data back into database
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Validate()
[highlight #FCE94F]Me.myDA.Update(Me.myDataSet.Tables("MyTable"))
[/highlight]
Me.myDataSet.AcceptChanges()
End Sub
End Class
[highlight #FCE94F][/highlight]
I am using Access 2010 and vs2013 express.
Imports System.Data.OleDb
Public Class Form1
Dim myDA As OleDbDataAdapter
Dim myDataSet As DataSet
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=|DataDirectory|\test.mdb") ' Use relative path to database file
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Table1", con)
con.Open()
myDA = New OleDbDataAdapter(cmd)
'Here one CommandBuilder object is required.
myDA.UpdateCommand = New OleDbCommand("UPDATE Table1 SET Field1 = ?, Field2 = ?")
'It will automatically generate DeleteCommand,UpdateCommand and InsertCommand for DataAdapter object
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "Table1")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
End Sub
' Save data back into database
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Validate()
[highlight #FCE94F]Me.myDA.Update(Me.myDataSet.Tables("MyTable"))
[/highlight]
Me.myDataSet.AcceptChanges()
End Sub
End Class
[highlight #FCE94F][/highlight]