How to update SQLite database from DataGridView in Visual Basic 2013 .net? - vb.net

I am displaying data from SQLite table into a DataGridView as following -
Private Sub Subjects_Manager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SQLiteConnection("Data Source = c:\demo\test.db;Version=3;")
con.Open()
sql = "SELECT * FROM med_subjects"
da = New SQLiteDataAdapter(sql, con)
da.Fill(ds, "SubjectsList")
DataGridView1.DataSource = ds.Tables("SubjectsList").DefaultView
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Subject Id"
.Columns(1).HeaderCell.Value = "Subject Name"
End With
DataGridView1.Sort(DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
con.close()
End Sub
I want to save changes done in DataGridView (either Updation of Row/s or Insertion of Row/s) back to SQLite table. But I couldn't find a way to do so.
Edit 1 :
I know Insert/Update Queries of SQLite, but what I don't know is how & where to keep them so that they can be triggered in responses to changes made in DataGridView. e.g.
' I am using this variable for demonstration, in reality InsertSubjectSqlString will be equal to changes done in DataGridView
Dim InsertSubjectSqlString As String = "Insert into med_subjects (Subject_Name) Values ('_Miscellaneous')"
Dim SqliteInsertRow As SQLiteCommand
SqliteInsertRow = con.CreateCommand
SqliteInsertRow.CommandText = InsertSubjectSqlString
SqliteInsertRow.ExecuteNonQuery()
But I don't know, where should I put it?
Edit 2:
After seeing comments and answers, I came to know that there is No direct way to Insert/Update Sqlite database from DataGridView. So I was curious, if there is any event like RowSelected which would
trigger on selecting a row and get that row's data
then taking the row's data into multiple text boxes and lastly
triggering Insert/Update queries taking values from these textboxes
by a button
I know it's highly hypothetical with NO sample codes, but it's because I am asking for Event name.

Call this on LeaveRow event or CellEndEdit
Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
Dim i as integer
Try
for i = 0 to datagrid.rows.count-1
myUpdate(datagrid.item(0,i).tostring() , datagrid.item(1,i).tostring())
next
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
note , you can also give the column name of your grid in place of column index , like this datagrid.item("fname",i).tostring()
Here we will save in database:
Sub myUpdate(byval fname as string , byval lname as string)
Try
dim con as new sqlconnection("you connection string")
dim cmd as new sqlcommand
con.open()
cmd.connection= con
cmd.commandtext="insert into table (fname,lname) values (#fname,#lname)"
cmd.Parameters.AddWithValue("#fname", fname)
cmd.Parameters.AddWithValue("#lname", lname)
cmd.ExecuteNonQuery()
Con.close()
Catch ex As Exception
MsgBox(Err.Description)
End Try
End sub
I hope this will help you to solve !
There are many ways to manipulate data .
CristiC

I dont think you will find some magic way that the DataGridView and DataTable are going to persist things automatically to the backend SQLite database. As you are hinting at I think you will have to rely on events.
I think the event you are missing is answered here stackoverflow cell value changed event

Ok I think is better to use CellEndEdit, because LeaveRow is triggered only if you click on other row.
Look on this example.
you must use: da.Update(ds.Tables("SubjectsList").DefaultView)
Imports System.Data.SqlClient
Public Class Form1
Const connectionstring As String = "server=(local);database=TestDB;uid=sa;pwd=sa;"
Private SQL As String = "select * from customer"
Private con As New SqlConnection(connectionstring)
Private dt As New DataTable
Private adapter As New SqlDataAdapter(SQL, con)
Private commandbuilder As New SqlCommandBuilder(adapter)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
adapter.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
adapter.Update(dt)
End Sub
End Class

Please use this code hopefully it will work
Imports System.Data.SQLite
Public Class Form
Dim con As New SQLite.SQLiteConnection
Dim da As New SQLite.SQLiteDataAdapter
Dim dt As New DataTable
Dim cmdbl As New SQLite.SQLiteCommandBuilder
Dim dlgResult As DialogResult
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
dlgResult = MessageBox.Show("Do you want to save the changes you made?", "Confirmation!", MessageBoxButtons.YesNo)
If dlgResult = DialogResult.Yes Then
Try
con.Open()
cmdbl = New SQLiteCommandBuilder(da)
da.Update(dt)
MsgBox("Updated successfully!")
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
End Sub
End Class

Related

Delete selected row from DataGridView and MS-Access Database

I am trying to delete the selected row from DataGridView and MS-Access database..
Private Sub ButtonEditDelete_Click(sender As Object, e As EventArgs) Handles ButtonEditDelete.Click
If Not Connection.State = ConnectionState.Open Then
Connection.Close()
End If
Try
If Me.DataGridViewEdit.Rows.Count > 0 Then
If Me.DataGridViewEdit.SelectedRows.Count > 0 Then
Dim intStdID As Integer = Me.DataGridViewEdit.SelectedRows(0).Cells("Username").Value
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Johnster\documents\visual studio 2015\Projects\Cash register\Cash register\Database11.accdb;Jet OLEDB:Database Password="
Connection.Open()
Command.Connection = Connection
Command.CommandText = "DELETE From MasterUser WHERE ID=? And Username=? And UserFullname=? AND Password=?"
Dim res As DialogResult
res = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res = DialogResult.Yes Then
Command.ExecuteNonQuery()
Else : Exit Sub
End If
Connection.Close()
End If
End If
Catch ex As Exception
End Try
End Sub
Replace your (Try) Part with this code:
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Johnster\documents\visual studio 2015\Projects\Cash register\Cash register\Database11.accdb;Jet OLEDB:Database Password=")
cn.Open()
Try
For Each row As DataGridViewRow In DataGridViewEdit.SelectedRows
Using cm As New OleDbCommand
cm.Connection = cn
cm.CommandText = "DELETE * FROM CheckDJ WHERE [Username]= #myuser"
cm.CommandType = CommandType.Text
cm.Parameters.AddWithValue("#myuser", CType(row.DataBoundItem, DataRowView).Row("Username"))
cm.ExecuteNonQuery()
End Using
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
cn.Close()
End Using
then clear your datasource of datagridview by this line:
DataGridViewEdit.Datasource = nothing
then repeat the code part that is responsible of filling the datagridview from the database
You are going about this in very much the wrong way. The proper way to do it would be to use an OleDbDataAdapter to populate a DataTable, bind that to a BindingSource and bind that to your DataDridView. You can then call RemoveCurrent on the BindingSource to set the RowState of the DataRow bound to the selected DataGridViewRow to Deleted. You then use the same OleDbDataAdapter to save the changes from the DataTable back to the database. The Fill method of the data adapter retrieves data and the Update method saves changes. You can call Update every time there's a change to save or you can let the user make all there changes locally first and then save them all in a single batch. Here's a code example:
Private connection As New OleDbConnection("connection string here")
Private adapter As New OleDbDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem",
connection)
Private builder As New OleDbCommandBuilder(adapter)
Private table As New DataTable
Private Sub InitialiseDataAdapter()
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
End Sub
Private Sub GetData()
'Retrieve the data.
adapter.Fill(table)
'Bind the data to the UI.
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Sub
Private Sub SaveData()
'Save the changes.
adapter.Update(table)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitialiseDataAdapter()
GetData()
End Sub
Private Sub deleteButton_Click(sender As Object, e As EventArgs) Handles deleteButton.Click
BindingSource1.RemoveCurrent()
End Sub
Private Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
SaveData()
End Sub
In certain circumstances, you may not be able to use an OleDbCommandBuilder and would have to create the InsertCommand, UpdateCommand and DeleteCommand yourself.

Problem with Windows Form and Access Database

First post here. I'm actually new to the world of programming and what I ask could look silly to many of you.
Anyway I'm trying to create a Form that will search into a Database the name you're looking for, showing a list of information about that person.
Problem comes when there's more than one person with that name in the database: in that case, the form only shows one of them. I wanted to add a button to get to the next result, but that's where I'm stuck.
I looked on the web for similar problems, but couldn't find any.
Here's my code, hope someone could help me
(please keep in mind I'm new and I don't know much about programming yet).
Form1:
Private Sub BtnCerca_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnCerca.Click
Dim trova As Boolean
Try
cm = New OleDb.OleDbCommand
With cm
.Connection = cn
.CommandType = CommandType.Text
.CommandText = "SELECT * FROM persone WHERE nome = '" & txtSearch.Text & "' OR cognome = '" & txtSearch.Text & "'"
dr = .ExecuteReader
End With
While dr.Read()
txtId.Text = dr("id_persone").ToString
txtNome.Text = dr("nome").ToString
txtCognome.Text = dr("cognome").ToString
txtDate.Text = dr("data_nascita").ToString
txtNascita.Text = dr("luogo_nascita").ToString
txtResidenza.Text = dr("luogo_residenza").ToString
trova = True
End While
If trova = False Then Dim unused = MsgBox("UTENTE NON TROVATO!", MsgBoxStyle.Critical)
dr.Close()
Catch ex As Exception
End Try
Exit Sub
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call Connection()
End Sub
Private Sub BtnReset_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnReset.Click
ClearTextFields(Me)
End Sub
Public Sub ClearTextFields(ByVal parent As Control)
For Each ctl As Control In parent.Controls
If TypeOf ctl Is TextBox Then
If ctl.Text.Trim() <> String.Empty Then
ctl.Text = String.Empty
End If
End If
Next
End Sub
End Class
Module:
Imports System.Data.OleDb
Module modConnection
Public cn As New OleDb.OleDbConnection
Public cm As New OleDb.OleDbCommand
Public dr As OleDbDataReader
Public Sub Connection()
cn = New OleDb.OleDbConnection
With cn
.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\dati_persone.mdb"
.Open()
End With
End Sub
End Module
In the form design view, drag and drop the BindingNavigator onto your form. You will find this in the Toolbox under the Data node. You can remove the + button and the X button by right clicking and choosing Delete from the context menu.
We will use a DataTable since that can be used as a DataSource for the BindingSource.
Keep your data objects local to the method where they are used so you can be sure they are closed and disposed. A Using block takes care of this for you. The Using block here includes both the connection and the command.
Always use parameters to avoid sql injection which can damage your database.
Create a BindingSource and set its DataSource to the DataTable. Then set the BindingSource property of the BindingNavigator you added to the form. Next add the DataBindings to each of your text boxes. The .Add method takes the name of the property to bind to, the BindingSource, and the field name.
That should do it.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Try
Using cn As New OleDbConnection("your connection string"),
cmd As New OleDbCommand("Select * From persone Where nome = #nome Or cognome = #cognome;", cn)
cmd.Parameters.Add("#nome", OleDbType.VarChar).Value = txtSearch.Text
cmd.Parameters.Add("#cognome", OleDbType.VarChar).Value = txtSearch.Text
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Dim BdS As New BindingSource
BdS.DataSource = dt
BindingNavigator1.BindingSource = BdS
txtId.DataBindings.Add("Text", BdS, "id_persone")
txtNome.DataBindings.Add("Text", BdS, "nome")
txtCognome.DataBindings.Add("Text", BdS, "cognome")
txtDate.DataBindings.Add("Text", BdS, "data_nascita")
txtNascita.DataBindings.Add("Text", BdS, "luogo_nascita")
txtResidenza.DataBindings.Add("Text", BdS, "luogo_residenza")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Indicate combobox values with a specific ids?

I made a Sub that will populate my combobox with loan descriptions. I want to get the loancode of the loandescription on selectedindexchanged without querying again the database. Is this possible? Or should I query the database to get the indicated loancode?
Private Sub LoanProducts()
Using cmd As New SqlClient.SqlCommand("SELECT loancode,loandescription FROM LoanProducts", gSQlConn)
Dim dt As New DataTable
Dim da As New SqlClient.SqlDataAdapter
dt.Clear()
da.SelectCommand = cmd
da.Fill(dt)
For Each row As DataRow In dt.Rows
CmbLoanAvail.Items.Add(row("loandescription"))
Next row
End Using
End Sub
Expected output:
Everytime the combobox index changed, the loancode of the selected loandescription will be displayed to a textbox.
Set DataTable to combobox .DataSource property and populate .ValueMember and .DisplayMember properties with corresponding column names.
Private Sub LoanProducts()
Dim query As String = "SELECT loancode, loandescription FROM LoanProducts"
Using command As New SqlCommand(query, gSQlConn)
Dim data As New DataTable
Dim adapter As New SqlClient.SqlDataAdapter With
{
.SelectCommand = cmd
}
adapter.Fill(data)
CmbLoanAvail.ValueMember = "loancode"
CmbLoanAvail.DisplayMember = "loandescription"
CmbLoanAvail.DataSource = data
End Using
End Sub
You can use SelectionChangeCommitted event to execute some action when user made a selection
Private Sub comboBox1_SelectionChangeCommitted(
ByVal sender As Object, ByVal e As EventArgs) Handles comboBox1.SelectionChangeCommitted
Dim combobox As ComboBox = DirectCast(sender, ComboBox)
Dim selectedCode As String = combobox.SelectedValue.ToString() // returns 'loancode'
End Sub
If you could get DB rows as strongly typed classes, you could make use of ItemSource, DisplayMember and ValueMember, which would solve your problem.
In case you presented, you can use SelectedIndex property of ComboBox. Also, you need to store resultset in some class field (preferably Pirvate one). See example code below:
Public Class Form4
Private _result As DataTable
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
dt.Columns.Add("col1")
dt.Columns.Add("col2")
dt.Rows.Add("val11", "val12")
dt.Rows.Add("val21", "val22")
' at this point, we got our result from DB
_result = dt
For Each row As DataRow In dt.Rows
ComboBox1.Items.Add(row("col1"))
Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim selectedIndex = ComboBox1.SelectedIndex
Dim selectedRow = _result(selectedIndex)
End Sub
End Class
Keep your database objects local to the method where they are used so you can ensure that they are closed and disposed. Note the comma at the end of the first Using line. This includes the command in the same Using block.
Set the DataSource, DisplayMember and ValueMember after the Using block so the user interface code doesn't run until the connection is disposed.
To get the loan code you simply access the SelectValue of the ComboBox.
Private Sub LoanProducts()
Dim dt As New DataTable
Using gSqlConn As New SqlConnection("Your connection string"),
cmd As New SqlClient.SqlCommand("SELECT loancode,loandescription FROM LoanProducts", gSqlConn)
gSqlConn.Open()
dt.Load(cmd.ExecuteReader)
End Using
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "loandescription"
ComboBox1.ValueMember = "loancode"
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
MessageBox.Show($"The Loan Code is {ComboBox1.SelectedValue}")
End Sub

VB2010 & MSACCESS | Object reference not set to an instance of an object

i'm making a login form and every time i try to login(whether with a correct or not user) it gives me the same error.
"Object reference not set to an instance of an object"
Here's the code:
Public Class login
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Fausto\Documents\GitHub\CRE\cre.accdb;")
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=#p_userid AND PASSWORD=#p_passw;"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
Dim da As New OleDb.OleDbDataAdapter
Private Sub login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'I figured how to make comments in VB! Yeey
'Temporarely redirecting to menuForm
With cmd
.Parameters.AddWithValue("p_userid", username.Text)
.Parameters.AddWithValue("p_passw", password.Text)
End With
Try
conn.Open()
Dim usr As String = cmd.ExecuteScalar.ToString
If Not (IsDBNull(usr)) AndAlso usr = username.Text Then
Me.DialogResult = Windows.Forms.DialogResult.OK
Else
Me.DialogResult = Windows.Forms.DialogResult.Cancel
End If
Catch ex As Exception
MsgBox("Could not connect to DB hahahaha" & Environment.NewLine & "Error message: " & ex.Message)
Me.DialogResult = Windows.Forms.DialogResult.Cancel
Finally
conn.Close()
Me.Close()
End Try
End Sub
Private Sub closeBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeBtn.Click
End
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
credits.Show()
End Sub
End Class
I'm using Visual Basic Express and Microsoft Access 2010,
Thanks :D
I saw several issues, but I think the one addressed in the question is here:
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Fausto\Documents\GitHub\CRE\cre.accdb;")
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=#p_userid AND PASSWORD=#p_passw;"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
The problem is that those variables are class-level, initialized prior to the class constructor, and the order in which the variables are initialized is not guaranteed. What is happening is that, at the point when the New OleDb.OleDbCommand(sql, conn) code executes, the conn variable is not guaranteed to have initialized.
This omission will fly under the radar, all the way until you try to execute a command, here:
Dim usr As String = cmd.ExecuteScalar.ToString
Aside from needing parentheses for the function call, it's not unil this point that the OleDbCommand object finally tries to use the connection supplied earlier and discovers that there's Nothing there.
While I have your attention, I also need to point out that you're using the wrong parameter notation for OleDb (you need to use ? placeholders instead of #NameParameters). Also, this is a horrible way to handle authentication. NEVER store a password in plain text like that.

Can not Search in and Edit DB in the same times (and same Windows Form) by using DataGridView

I'm have DataGridView in a Windows Form with some data in it and I have button for edit, I want to search for row by using TextBox and button and when I find the wanted row I will change it and click edit button,when I edit any row (without using search button) and press edit the DB is Updated , my problem is that: when I search for specific row and find it then edit the data and press edit button the data in DB don't updated, please help, I'm use this code:
Imports System.Data.SqlClient
Public Class Form9
Private sqlConn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Clinic System\Clinic System\ClinicDB.mdf;Integrated Security=True;User Instance=True")
Private cmdSelect, cmdDelete As String
Private daEmployees As New SqlDataAdapter("Select * From History", sqlConn)
Private sqlCmndBuilder As New SqlCommandBuilder(daEmployees)
Private myDS As New DataSet
Private Sub HistoryBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Validate()
Me.HistoryBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.ClinicDBDataSet3)
End Sub
Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
daEmployees.Fill(myDS, "History")
HistoryDataGridView.DataSource = myDS.Tables(0)
End Sub
Private Sub ButtonSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSearch.Click
Try
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Clinic System\Clinic System\ClinicDB.mdf;Integrated Security=True;User Instance=True")
Dim d1 As New SqlDataAdapter("Select * from History Where Name like '%" & TextBox1.Text & "%'", con)
Dim d2 As New DataTable
d1.Fill(d2)
HistoryDataGridView.DataSource = d2
Catch ex As Exception
MessageBox.Show("Err.Discription")
End Try
End Sub
Private Sub ButtonEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonEdit.Click
daEmployees.Update(myDS.Tables(0))
MsgBox("Patient Details Updated!")
End Sub
Your issue is rather simple - you trying to update wrong table
daEmployees.Update(myDS.Tables(0))
While you need to update d2
In form scope
Dim _isSearch as boolean
On Form9_Load and when you reload as well
_isSearch = false
Here what you can do - In ButtonSearch_Click
_isSearch = true
If myDS.Tables.Contains("SEARCH_TBL") Then
myDS.Tables.Remove("SEARCH_TBL")
End if
Dim d2 As DataTable = myDS.Tables.Add("SEARCH_TBL")
d1.Fill(d2)
In ButtonEdit_Click
if _isSearch then
daEmployees.Update(myDS.Tables("SEARCH_TBL"))
else
daEmployees.Update(myDS.Tables(0))
End if
I think, daEmployees should update "SEARCH_TBL" because result set identical to first table. If not, just take your other adapter to a form scope.
But really, you can reuse the grid and update button, but you need to create logic tracking which table is currently loaded.