Hello there,
I wrote the below code to save data entered to DataGridView to database, the code works fine, but when I shut down the application and run it again, the new data disappear! where is the problem? Thanks
I wrote the below code to save data entered to DataGridView to database, the code works fine, but when I shut down the application and run it again, the new data disappear! where is the problem? Thanks
VB.NET:
Imports System.Data.OleDb
Public Class frmDataInsertionForm
Dim Con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=sales.mdb")
Dim ItemsDataSet As New DataSet
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub frmDataInsertionForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With DGV
.ColumnCount = 4
.Columns(0).HeaderText = "Item Description"
.Columns(0).Width = 300
.Columns(1).HeaderText = "Item UOM"
.Columns(2).HeaderText = "Item Category"
.Columns(3).HeaderText = "Item Barcode"
End With
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try
Con.Open()
Dim DBAdapter As New OleDbDataAdapter("select * from Items", Con)
ItemsDataSet.Clear()
DBAdapter.Fill(ItemsDataSet, "Items")
Dim DataBuilder As New OleDbCommandBuilder(DBAdapter)
' loop to get all items in DGV
For i As Integer = 0 To DGV.RowCount - 2
Dim NewRow As DataRow = ItemsDataSet.Tables("Items").NewRow
With NewRow
.Item(1) = DGV.Rows(i).Cells(0).Value 'Item Description
.Item(2) = 0 'Item Quantity
.Item(3) = 0 'Item Unit Cost Price
.Item(4) = 0 'Item Unit Selling Price
.Item(5) = DGV.Rows(i).Cells(1).Value 'Item UOM
.Item(6) = DGV.Rows(i).Cells(2).Value 'Item Category
.Item(7) = DGV.Rows(i).Cells(3).Value 'Item Barcode
End With
' Do get the entered data and put them in the new record:
ItemsDataSet.Tables("Items").Rows.Add(NewRow)
'Now update the adapter
DBAdapter.Update(ItemsDataSet, "Items")
Dim Cmdb = New OleDbCommandBuilder(DBAdapter)
Next
DGV.Rows.Clear()
MsgBox("Items saved.")
DGV.Focus()
Con.Close()
Catch ex As Exception
MsgBox("error" & ex.ToString)
End Try
End Sub
End Class