How to pass arraylist to stored procedure in VB - vb.net

How to pass an ArrayList to the stored procedure in this code below
Dim sqlcon As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("connect").ConnectionString)
Dim sda As New SqlDataAdapter
Dim cmd As New SqlCommand
Dim dt As New DataTable
Dim arr As New ArrayList
arr.Add("#type,1") '--------------How do I pass this to my stored procedure
cmd = New SqlCommand("usp_demo", sqlcon)
cmd.CommandType = CommandType.StoredProcedure
sda.SelectCommand = cmd
sda.Fill(dt)
Below is the Stored Procedure used - "usp_demo"
alter procedure usp_demo
#type int
As
Begin
If #type = 1
Begin
select * from sample
End
If #type = 2
Begin
select * from nextnode
End
End

The design of this code depends on how many parameters you need to pass. We don't want the user interface code worrying about the database so we don't want to create SqlParameters in the UI. Let's say you have 5 parameters of different types. Just pass the values to the Function. If there are many parameters, create a class for the entity. Pass an instance of the class with the properties set in the UI code. You could even pass a List(Of YourClass) and loop through it resetting the .Value property of the Parameters.
Simple method as per your question.
Private Function GetData(type As Integer) As DataTable
Dim dt As New DataTable
Using sqlcon As New SqlConnection(),
cmd As New SqlCommand("usp_demo", sqlcon)
cmd.Parameters.Add("#type", SqlDbType.Int).Value = type
cmd.CommandType = CommandType.StoredProcedure
sqlcon.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Usage
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetData(1)
DataGridView1.DataSource = dt
End Sub
More than on parameter
Private Function InsertRecord(FName As String, LName As String) As Integer
Dim i As Integer
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("connect").ConnectionString),
cmd As New SqlCommand("Insert Into Employee (FirstName, LastName) Values (#First, #Last);", cn)
cmd.Parameters.Add("#First", SqlDbType.NVarChar, 100).Value = FName
cmd.Parameters.Add("#Last", SqlDbType.NVarChar, 100).Value = LName
cn.Open()
i = cmd.ExecuteNonQuery
End Using
Return i
End Function
usage
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim i = InsertRecord("John", "Smith")
If i = 1 Then
MessageBox.Show("Success")
Else
MessageBox.Show("Error")
End If
End Sub
Create a class
Public Class Employee
Public Property FirstName As String
Public Property MiddleName As String
Public Property LastName As String
Public Property DOB As Date
Public Property Weight As Integer
Public Property Department As String
Public Property IsHourly As Boolean
Public Property Rate As Decimal
Public Sub New(FName As String, MName As String, LName As String, Birth As Date, lbs As Integer, Dep As String, Hourly As Boolean, Pay As Decimal)
FirstName = FName
MiddleName = MName
LastName = LName
DOB = Birth
Weight = lbs
Department = Dep
IsHourly = Hourly
Rate = Pay
End Sub
End Class
This class could probably be used other ways in your application.
Private Function InsertCompleteEmployee(e As Employee) As Integer
Dim i As Integer
Dim sql = "Insert Into EmployeeComplete (FirstName, MiddleName, LastName, DOB, Weight, Department, IsHourly, Rate) Values (#FName, #MName, #LName, #Birth, #lbs, #Dep, #Hourly, #Rate);"
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("connect").ConnectionString),
cmd As New SqlCommand(sql, cn)
With cmd.Parameters
.Add("#FName", SqlDbType.NVarChar, 100).Value = e.FirstName
.Add("#MName", SqlDbType.NVarChar, 100).Value = e.MiddleName
.Add("#LName", SqlDbType.NVarChar, 100).Value = e.LastName
.Add("#Birth", SqlDbType.Date).Value = e.DOB
.Add("#lbs", SqlDbType.Int).Value = e.Weight
.Add("#Dep", SqlDbType.NVarChar, 100).Value = e.Department
.Add("#Hourly", SqlDbType.Bit).Value = e.IsHourly
.Add("#Rate", SqlDbType.Decimal).Value = e.Rate
End With
cn.Open()
i = cmd.ExecuteNonQuery
End Using
Return i
End Function
Usage
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Emp As New Employee(TextBox1.Text, TextBox2.Text, TextBox3.Text, DateTimePicker1.Value, 200, "Accountin", CheckBox1.Checked, 8.5D)
Dim i = InsertCompleteEmployee(Emp)
If i = 1 Then
MessageBox.Show("Success")
Else
MessageBox.Show("Error")
End If
End Sub
The Using...End Using blocks ensure that your database objects are closed and disposed. In these Functions both the connection and the command are part of the block. Note the comma at the end of the Using line.
Always use parameters to avoid sql injection and make the sql string easier to write.

Personally i generally use a key value pair [KeyValuePair(Of String, List(Of SqlParameter))]; I hope that's what you were looking for; probably someone will have a better solution
Public Function ExecuteSelectionSP(ByVal MyConnectionString As String, ByVal KVP As KeyValuePair(Of String, List(Of SqlParameter)), ByRef MyTable As DataTable) As Boolean
Dim Result As Boolean
Dim sqlcon As New SqlConnection(MyConnectionString)
Dim reader As SqlDataReader
Dim cmd As New SqlCommand
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = KVP.Key
For Each MyParameter As SqlParameter In KVP.Value
cmd.Parameters.Add(MyParameter)
Next
cmd.Connection = sqlcon
Try
If sqlcon.State = ConnectionState.Closed Then sqlcon.Open()
reader = cmd.ExecuteReader()
MyTable.Load(reader)
If sqlcon.State = ConnectionState.Open Then sqlcon.Close()
Result = True
Catch ex As Exception
MsgBox("Execution error :" & vbCrLf & KVP.Key & vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.Critical, "Errore")
Result = False
End Try
Return Result
End Function

Related

system login using query select 1

I am trying to code the login page, here is my code:
'login form code
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim username As String = txtUsername.Text.Trim
Dim pwd As String = txtPassword.Text.Trim
Dim insertQry As String = "select 1 from UserInfo where username = '" & username & "' and userpassword = '" & pwd & "'"
Dim res As Boolean = executeReader(insertQry)
End Sub
database module
Imports System.Data.SqlClient
Module DBconn
Public conn_ As New SqlConnection("")
Public Function executeReader(ByVal query As String)
Try
Dim cmd As New SqlCommand(query, conn_)
conn_.Open()
Dim r2 As SqlDataReader = cmd.ExecuteReader()
Return True
Catch ex As Exception
Return False
End Try
End Function
End Module
My question is how to do validation of username and password check with select 1 query?
Take a look at this example, it does the following:
It returns the count of the primary key value in the SQL query (documentation)
It uses parameters to pass the values to the WHERE clause (documentation)
It uses ExecuteScalar to return a single value from the command (documentation)
Private Function ValidateLogin(ByVal username As String, ByVal password As String) As Boolean
Dim count As Integer = 0
'Declare the connection object
Using con As SqlConnection = New SqlConnection
'Wrap code in Try/Catch
Try
'Set the connection string
con.ConnectionString = "" 'TODO: set this value
'Create a new instance of the command object
Using cmd As SqlCommand = New SqlCommand("SELECT Count(UserInfoId) FROM UserInfo WHERE username=#username AND userpassword=#password", con)
'Parameterize the query
With cmd.Parameters
.Add("#username", SqlDbType.VarChar).Value = username
.Add("#password", SqlDbType.VarChar).Value = password
End With
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
count = Convert.ToInt32(cmd.ExecuteScalar())
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
End If
End Try
End Using
'Return row count is greater than 0
Return count > 0
End Function

where should i put the button save codes into this codes that i sent here? because i'd like to save into another table

i put this code because i used combobox and they fill my two textbox,but when try to save its not saving the data that i put
this is the code
Sub loaddata()
Try
reload("SELECT * FROM NAME", STUDENT)
STUDENT.DataSource = dt
STUDENT.DisplayMember = "NAME"
STUDENT.ValueMember = "ID"
Catch ex As Exception
End Try
End Sub
Private Sub NAME_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NAME.SelectedIndexChanged
Try
Dim sql As String
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
strcon.Open()
sql = "SELECT * FROM STUDENT where NAME LIKE '%" & NAME.Text & "%'"
cmd.Connection = strcon
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
GENDER.Text = dt.Rows(0).Item("GENDER").ToString
ADDRESS.Text = dt.Rows(0).Item(" ADDRESS").ToString
End If
Catch ex As Exception
Finally
strcon.Close()
End Try
End Sub
please show me how to put the save codes here,because i use only the BindingNavigator1 to save, but it does not save, sorry if my grammar is wrong because i'm not a fluent in english
I know we have a language barrier but we are both trying our best. I have provided a few examples of code to interact with a database.
It is a good idea to keep you database code separate from you user interface code. If you want to show a message box in you Try code, keep the Try in the user interface code. The error will bubble up from the database code to the calling code.
Using...End Using blocks take care of disposing of database objects. Parameters protect against Sql injection because parameter values are not considered executable code by the database. Note that for OleDb data sources the order that the parameters appear in the sql statement must match the order that they are added to the Parameters collection.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim dt = GetOriginalData()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = dt
End Sub
Private Function GetOriginalData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your first connection string"),
cmd As New OleDbCommand("Select ID, Name From Table1;")
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
InsertData(CInt(ComboBox1.SelectedValue), ComboBox1.SelectedText, txtGender.Text, txtAddress.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub InsertData(id As Integer, name As String, gender As String, address As String)
Using cn As New OleDbConnection("Your second connection string"),
cmd As New OleDbCommand("Insert Into Table2 (ID, Name, Gender, Address) Values (#ID, #Name, #Gender, #Address);", cn)
With cmd.Parameters
.Add("#ID", OleDbType.Integer).Value = id
.Add("#Name", OleDbType.VarChar).Value = name
.Add("#Gender", OleDbType.VarChar).Value = gender
.Add("#Address", OleDbType.VarChar).Value = address
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

System.InvalidOperationException: 'Operation is not valid due to the current state of the object.' on a update query in vb.net

Hello I am trying to do an update query on my database however I end up with this error message
System.InvalidOperationException: 'Operation is not valid due to the current state of the object.'
Here is the code for my search query which I then use in the update
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID = #ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
End Using
Return dt
End Function
This is the ToTextBox function
Public Sub ToTextbox(ByVal newdt)
txtFName.Text = newdt.Rows(0)(1).ToString()
txtLName.Text = newdt.Rows(0)(2).ToString()
mtxtContactNumber.Text = newdt.rows(0)(3).ToString()
txtAddress.Text = newdt.rows(0)(4).ToString()
txtTown.Text = newdt.rows(0)(5).ToString()
txtPostCode.Text = newdt.rows(0)(6).ToString()
End Sub
And the update function
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
con.Open()
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
con.Close()
End Using
Return Result
End Function
And the Update button
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I believe you update problems are solved in comments.
You still have too much stuff in your DataAccess code. Just return the DataTable and use it in the user interface code.
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID = #ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = SearchData(FirstNameTextBox.Text, CInt(IDTextBox.Text))
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
End Sub
Public Sub ToTextbox(ByVal newdt As DataTable)
txtFName.Text = newdt.Rows(0)(1).ToString()
txtLName.Text = newdt.Rows(0)(2).ToString()
mtxtContactNumber.Text = newdt.Rows(0)(3).ToString()
txtAddress.Text = newdt.Rows(0)(4).ToString()
txtTown.Text = newdt.Rows(0)(5).ToString()
txtPostCode.Text = newdt.Rows(0)(6).ToString()
End Sub

VB.Net SQL Count Statement into a label

I'm trying to count the students whose teacher where teacher = '" & lblTeacher.Text & "'"
EXAMPLE :
Public Class Form1
Dim conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Richard\Desktop\Dbase.mdb"
Dim con As New OleDbConnection
Dim da, da1 As New OleDbDataAdapter
Dim dt, dt1 As New DataTable
Dim sql As String
Dim ds As New DataSet
Public Sub display()
sql = "select * from Info"
dt.Clear()
con.Open()
da = New OleDbDataAdapter(sql, con)
da.Fill(dt)
con.Close()
DataGridView1.DataSource = dt.DefaultView
End Sub
Public Sub count()
sql = "select COUNT(name) from Info where teacher = '" & lblTeacher.Text & "'"
da1 = New OleDbDataAdapter(sql, con)
ds.Clear()
con.Open()
da.Fill(ds)
lblCount.Text = ds.Tables(0).Rows.Count.ToString
con.Close()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = conn
display()
End Sub
Private Sub DataGridView1_Click(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Click
lblTeacher.Text = DataGridView1.CurrentRow.Cells("teacher").Value.ToString
count()
End Sub
End Class
1:
Try this instead of your current count() method. Pay special attention to my comments; they address some poor practices from the original code:
' Better functional style: accept a value, return the result
Public Function GetStudentCount(teacher As String) As Integer
'**NEVER** use string concatenation to put data into an SQL command!!!
Const sql As String = "select COUNT(name) from Info where teacher = ?"
'Don't try to re-use the same connection in your app.
' It creates a bottleneck, and breaks ADO.Net's built-in connection pooling,
' meaning it's more likely to make object use *worse*, rather than better.
'Additionally, connection objects should be created in a Using block,
' so they will still be closed if an exception is thrown.
' The original code would have left the connection hanging open.
Using con As New OleDbConnection(conn), _
cmd As New OleDbCommand(sql, con)
'This, rather than string concatenation, is how you should put a value into your sql command
'Note that this NEVER directly replaces the "?" character with the parameter value,
' even in the database itself. The command and the data are always kept separated.
cmd.Parameters.Add("teacher", OleDbType.VarChar).Value = teacher
con.Open()
' No need to fill a whole dataset, just to get one integer back
Return DirectCast(cmd.ExecuteScalar(), Integer)
'No need to call con.Close() manually. The Using block takes care of it for you.
End Using
End Function
Here it is again, without all the extra comments:
Public Function GetStudentCount(teacher As String) As Integer
Const sql As String = "select COUNT(name) from Info where teacher = ?"
Using con As New OleDbConnection(conn), _
cmd As New OleDbCommand(sql, con)
cmd.Parameters.Add("teacher", OleDbType.VarChar).Value = teacher
con.Open()
Return DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Function
Call it like this:
Private Sub DataGridView1_Click(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Click
lblTeacher.Text = DataGridView1.CurrentRow.Cells("teacher").Value.ToString()
lblCount.Text = GetStudentCount(lblTeacher.Text).ToString()
End Sub

How to Edit Datagrid Records and also in database

this is my code for loading the data from database to datagrid
Private Sub Records_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim connString As String = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Database3.Accdb;"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [userinfo] ORDER BY ID", MyConn)
da.Fill(ds, "userinfo") 'Change items to your database name
Dim cb = New OleDbCommandBuilder(da)
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
If RequiredEntry() = True Then
Return
End If
Try
Dim cn As New OleDbConnection("Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Database3.Accdb;")
If cn.State = ConnectionState.Closed Then cn.Open()
Dim sSQL As String = "insert into [userinfo]([username],[password],[FirstName],[LastName],[Account]) values(#username,#password,#FirstName,#LastName,#Account)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
' UserName
If txtPassword.Text = txtConfirm.Text Then
Dim username As OleDbParameter = New OleDbParameter("#username", OleDbType.VarWChar, 50)
username.Value = txtUser.Text.ToString()
cmd.Parameters.Add(username)
Else
MsgBox("Password not matched")
End If
'password
Dim password As OleDbParameter = New OleDbParameter("#password", OleDbType.VarWChar, 50)
password.Value = txtPassword.Text.ToString()
cmd.Parameters.Add(password)
'First Name
Dim FirstName As OleDbParameter = New OleDbParameter("#FirstName", OleDbType.VarWChar, 50)
FirstName.Value = txtFirstName.Text.ToString()
cmd.Parameters.Add(FirstName)
' Last Name
Dim LastName As OleDbParameter = New OleDbParameter("#LastName", OleDbType.VarWChar, 50)
LastName.Value = txtLastName.Text.ToString()
cmd.Parameters.Add(LastName)
'Account
Dim Account As OleDbParameter = New OleDbParameter("#Account", OleDbType.VarWChar, 50)
Account.Value = cboAccount.GetItemText(cboAccount.SelectedItem)
cmd.Parameters.Add(Account)
If cmd.ExecuteNonQuery() Then
cn.Close()
MessageBox.Show("New User is Added successfully.", "Record Saved")
Call clear()
Me.Hide()
FileMaintenance.Show()
Else
MsgBox("New User Addition Failed ", MsgBoxStyle.Critical, "Addition Failed")
Return
End If
Catch ex As Exception
Exit Sub
End Try
End Sub
Private Sub NewUser_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
e.SuppressKeyPress = e.Control
If e.KeyCode = Keys.Enter Then
SendKeys.Send("{tab}")
End If
End Sub
and this is my for delete
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
Dim connString As String = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Database3.Accdb;"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim rows As String
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = (ds.Tables)
rows = DataGridView1.SelectedRows(0).Cells(0).Value.ToString()
da = New OleDbDataAdapter("Delete * from [userinfo] where ID=" & rows, MyConn)
da.Fill(ds, "userinfo")
Records_Load(sender, e)
Catch ex As Exception
MessageBox.Show("cannot delete empty records")
End Try
how can i edit my data from datagrid view as well in my database
also how can i lock the datagrid from entering fields accidentally
Your code is very wrong. You're retrieving the data correctly in the first place but then you're inserting and deleting incorrectly.
The idea is that you use one data adapter for all four operations, i.e. select, insert, update and delete. That's why it has SelectCommand, InsertCommand, UpdateCommand and DeleteCommand properties. You call Fill and it executes the SQL in the SelectCommand to retrieve data into a DataTable. You are then supposed to make all the changes you want, i.e. insert, update and delete, to the data in that DataTable. When you're done, you call Update on the data adapter and it will execute the SQL in the InsertCommand, UpdateCommand and DeleteCommand as required to save all the changes back to the database. Here's an example I wrote a long time ago:
Private connection As New SqlConnection("connection string here")
Private adapter As New SqlDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem", _
connection)
Private table As New DataTable
Private Sub InitialiseDataAdapter()
Dim delete As New SqlCommand("DELETE FROM StockItem WHERE ID = #ID", Me.connection)
Dim insert As New SqlCommand("INSERT INTO StockItem (Name, Quantity, Unit) VALUES (#Name, #Quantity, #Unit)", Me.connection)
Dim update As New SqlCommand("UPDATE StockItem SET Name = #Name, Quantity = #Quantity, Unit = #Unit WHERE ID = #ID", Me.connection)
delete.Parameters.Add("#ID", SqlDbType.Int, 4, "ID")
insert.Parameters.Add("#Name", SqlDbType.VarChar, 100, "Name")
insert.Parameters.Add("#Quantity", SqlDbType.Float, 8, "Quantity")
insert.Parameters.Add("#Unit", SqlDbType.VarChar, 10, "Unit")
update.Parameters.Add("#Name", SqlDbType.VarChar, 100, "Name")
update.Parameters.Add("#Quantity", SqlDbType.Float, 8, "Quantity")
update.Parameters.Add("#Unit", SqlDbType.VarChar, 10, "Unit")
update.Parameters.Add("#ID", SqlDbType.Int, 4, "ID")
Me.adapter.DeleteCommand = delete
Me.adapter.InsertCommand = insert
Me.adapter.UpdateCommand = update
Me.adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
End Sub
Private Sub GetData()
'Retrieve the data.
Me.adapter.Fill(Me.table)
'The table can be used here to display and edit the data.
'That will most likely involve data-binding but that is not a data access issue.
End Sub
Private Sub SaveData()
'Save the changes.
Me.adapter.Update(Me.table)
End Sub
Note that this example was written for SQL Server but you simply swap out all the SqlClient types for OleDb types and it works for Access.
If you want to save changes immediately for some reason then you simply call Update after each change.
By the way, your connection string should be written like this:
Dim connString As String = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=|DataDirectory|\BackUp\Database3.Accdb;"