Hi,
I hope you want to know how to save your Datagridview data to your MS Access database using VB.Net. you can place one button in your windows forms then you can write insert operation inside the button click event the following code
Private Sub btnInsert_Click(sender As System.Object, e As System.EventArgs) Handles btnInsert.Click
For Each row As DataGridViewRow In dataGridView1.Rows
Dim sFileName As String = "C:\Users\Administrator\Desktop\Book1.xls"
Dim sConStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES';", sFileName)
Using connection As OleDbConnection = New OleDbConnection(sConStr)
Dim sql As String = "INSERT INTO [Sheet1$] VALUES(@ColParameter1, @ColParameter2, @ColParameter3;"
Using command As OleDbCommand = New OleDbCommand(sql, connection)
command.Parameters.AddWithValue("@ColParameter1", row.Cells("ColumnName1").Value)
command.Parameters.AddWithValue("@ColParameter2", row.Cells("ColumnName2").Value)
command.Parameters.AddWithValue("@ColParameter3", row.Cells("ColumnName3").Value)
connection.Open()
command.ExecuteNonQuery()
connection.Close()
End Using
End Using
Next
MessageBox.Show("Records added successfully.")
End Sub
Recommended:
1, you don't write connection string and file path for each method inside instead of that you can write the common declaration in the top of the class.
2, you can open the connection object before executing a query or execute reader then close it after executing a query or execute reader.
I hope it will help you