How can I make a datagridview live connected to an access database stored locally in VB.NET? - vb.net

I would like it so when I delete/edit a record from the datagridview, it will automatically delete/edit the access database file. Here is a snippet of my code which loads the database into the datagridview.
Public Function dbConnect() As Boolean
Try
cn = New OleDbConnection(DataBasePath)
cn.Open()
'MessageBox.Show("is work ")
Return True
Catch ex As Exception
MessageBox.Show("Unable to open the database: " & ex.Message)
Return False
End Try
End Function
Private Function GetOrders() As DataTable
Dim dtOrders As New DataTable
dbConnect()
Dim SQLCMD As New OleDbCommand
SQLCMD.Connection = cn
SQLCMD.CommandText = "Select * From [OrdersTbl]"
dtOrders.Load(SQLCMD.ExecuteReader())
Return dtOrders
End Function
Private Sub EditOrdersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OrdersDataGrid.DataSource = GetOrders()
End Sub
How can I make it so that changes are saved to the local file.

I have a datagridview and a button on the form. Here's the code you can refer to:
Private dt As DataTable = New DataTable
Private da As OleDbDataAdapter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connection As OleDbConnection = New OleDbConnection("your connection string")
connection.Open()
Dim cmdTxt As String = "SELECT * FROM yourTable"
da = New OleDbDataAdapter(New OleDbCommand(cmdTxt, connection))
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(dt)
Dim source As BindingSource = New BindingSource With {
.DataSource = dt
}
DataGridView1.DataSource = source
connection.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DataGridView1.EndEdit()
da.Update(dt)
End Sub
Every time you want to update database from your datagridview, just click the button.

Related

Insert, Delete, and Edit Data in DataGridView using single Update Button in Vb.net

I am trying to have a add, delete, and edit function in Vb.net by using one update button and changing the values in the datagridview manually then hitting update. However, I get an error stating
"System.InvalidOperationException: 'Update requires a valid UpdateCommand when passed DataRow collection with modified"
Any Ideas? The error comes next to the da.Update(changes)
Also in the above code not shown in my code I have load_data() in the private form1_load sub.
Here is code:
Dim da As New SqlDataAdapter
Dim dt As New DataSet
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim cmd As New SqlCommandBuilder
Dim changes As New DataSet
changes = dt.GetChanges
If changes IsNot Nothing Then
da.Update(changes)
da.Fill(dt)
DataGridView1.DataSource = dt.Tables(0)
End If
End Sub
Private Sub load_data()
Using connection = New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=vbconnectionfinal;Integrated Security=True")
da = New SqlDataAdapter("Select * From TrueTrack", connection)
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt.Tables(0)
End Using
End Sub
You are creating a SqlCommandBuilder but not associating it with a SqlDataAdapter, so what's the point? The whole purpose of a command builder is to automatically generate action commands when you call Update on a data adapter. When you create your data adapter, create the command builder immediately after and associate the two, which you would do by passing the data adapter as an argument to the constructor of the command builder.
The following code works for me.
Dim da As New SqlDataAdapter
Dim dt As New DataSet
Dim connection = New SqlConnection("connection string")
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cmd As New SqlCommandBuilder(da)
Dim changes As New DataSet
changes = dt.GetChanges
If changes IsNot Nothing Then
da.Update(changes)
DataGridView1.DataSource = dt.Tables(0)
End If
End Sub
Private Sub load_data()
Dim cmd As SqlCommand = New SqlCommand("Select * From TrueTrack", connection)
da = New SqlDataAdapter(cmd)
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt.Tables(0)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
load_data()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
connection.Close()
End Sub

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.

update database from data grid view in vb.net

i have a data grid view, filled by data from database now i need to change the data and update database.
Private daVD As New OracleDataAdapter
Private cmdJV As New OracleCommandBuilder
Private dtVD As New DataTable()
Dim cmd As New OracleCommand("Select JV_CODE,JV_ACC_NAME,DEBIT,CREDIT From VOUCHER_DETAIL where VOUCHERNO =:Vno", sgcnn)
cmd.Parameters.Add("#Vno", OracleDbType.NVarchar2).Value = txtJVNo.Text.ToString.Trim
dtVD.Clear()
daVD = New OracleDataAdapter(cmd)
daVD.Fill(dtVD)
dgvAccDetail.AutoGenerateColumns = False
dgvAccDetail.DataSource = dtVD
If dtVD.Rows.Count > 0 Then
For i As Integer = 0 To dtVD.Rows.Count - 1
''Dim DataType() As String = myTableData.Rows(i).Item(1)
dgvAccDetail.Rows(i).Cells(0).Value = dtVD.Rows(i).Item("JV_CODE").ToString.Trim
dgvAccDetail.Rows(i).Cells(1).Value = dtVD.Rows(i).Item("JV_ACC_NAME").ToString.Trim
dgvAccDetail.Rows(i).Cells(2).Value = dtVD.Rows(i).Item("DEBIT").ToString.Trim
dgvAccDetail.Rows(i).Cells(3).Value = dtVD.Rows(i).Item("CREDIT").ToString.Trim
Next
End If
i tried many different ways to update the database table but not working
Try
cmdJV = New OracleCommandBuilder(da)
daJV.Update(ds, "VJ_Details")
ds.AcceptChanges()
MessageBox.Show(" The record has been updated.")
Catch ex As Exception
MsgBox(ex.Message)
End Try
I have never used Oracle, but this is how you could do it using SQL Server (there are actually several ways to push data from a DatGridView to a table in SQL Server).
Here is one option for you to try.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=Server_Name\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Orders"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub DataGridView1_Click(sender As Object, e As EventArgs) Handles DataGridView1.Click
DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Orange
End Sub
End Class
Here is one more option for you to consider.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Server_Name\SQLEXPRESS;Database=Database_Name;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub

"No value given for one or more required parameters" VB.Net GridView Update

I'm having an Access DB and connecting to it through VB.NET.
First, I show a table records in GridView with the user having ability to update it. After the user updates, he will press a Button to take the updated data from the GridView and update the Access database.
But while doing that I get the error No value given for one or more required parameters. What I'm missing here?
Code:
Dim sConnectionString As String _
= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DB.accdb;Persist Security Info=False;"
Dim myConnection As OleDbConnection
Dim myAdapter As OleDbDataAdapter
Dim myTable As DataTable
Private Sub form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
myConnection = New OleDbConnection(sConnectionString)
Dim myCommand As New OleDbCommand("SELECT ID,Test FROM T1", myConnection)
myConnection.Open()
myAdapter = New OleDbDataAdapter(myCommand)
myTable = New DataTable()
myAdapter.Fill(myTable)
setDataGridDataSource(myTable)
setLabelTxt("Row Count: " + myTable.Rows.Count.ToString(), RowCount)
DataGridView1.AllowUserToAddRows = True
DataGridView1.AllowUserToDeleteRows = True
DataGridView1.EditMode = DataGridViewEditMode.EditOnEnter
myConnection.Close()
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Me.Validate()
Dim command As OleDbCommand = New OleDbCommand("UPDATE T1 SET ID = ? , Test = ? WHERE ID = ?;", myConnection)
myAdapter.UpdateCommand = command
myAdapter.Update(myTable)
myTable.AcceptChanges()
End Sub
Your sql command with text "UPDATE T1 SET ID = ? , Test = ? WHERE ID = ?;" expects 3 parameters, but your are not setting them anywhere in the code. See this example and assign parameters to your command as in:
cmd.Parameters.AddWithValue("ID", txtID.Text);
cmd.Parameters.AddWithValue("Test", txtTest.Text);
... and so on
The code should be edited to this:
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Me.Validate()
Dim cmdBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(myAdapter)
Dim changes As DataTable = myTable.GetChanges
If changes IsNot Nothing Then
myAdapter.Update(myTable)
End If
myTable.AcceptChanges()
End Sub

Displaying Data from SQL in TextBox by clicking ComboBox item in Visual Basic 2012

I have three columns in SQL, which I want the data displayed in three textboxes by clicking an item in ComboBox.
The issue is not really displaying. I can save the data fine and display. However, one of the text fields will only show one cell and not update when a different item is selected. Hope this is making sense.
Here is the code I have for saving:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO MyDiary (Title, DiaryContent, DiaryDate) VALUES (#Title, #DiaryContent, #DiaryDate)"
myconnect.Open()
Try
mycommand.Parameters.Add("#Title", SqlDbType.VarChar).Value = TextBox1.Text
mycommand.Parameters.Add("#DiaryContent", SqlDbType.VarChar).Value = TextBox2.Text
mycommand.Parameters.Add("#DiaryDate", SqlDbType.VarChar).Value = TextBox3.Text
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
And here is the code for displaying in form1:
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim ds As New DataSet
Dim da As New SqlDataAdapter
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Dim max As String
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'RioDiaryDataSet5.MyDiary' table. You can move, or remove it, as needed.
Me.MyDiaryTableAdapter.Fill(Me.RioDiaryDataSet5.MyDiary)
Dim con As New SqlConnection(" Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True")
Dim cmd As New SqlCommand("Select Title,DiaryContent,DiaryDate FROM MyDiary ")
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
cmd.Connection = con
da.Fill(ds, "MyDiary")
con.Open()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.DisplayMember = "Title'"
ComboBox1.ValueMember = "DiaryContent"
End Sub
Private Sub NewEntryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewEntryToolStripMenuItem.Click
AddEntry.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If (Not Me.ComboBox1.SelectedValue Is Nothing) Then
Me.TextBox2.Text = ComboBox1.Text
Me.TextBox3.Text = ComboBox1.SelectedValue.ToString
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("DiaryDate").ToString() 'Where ColumnName is the Field from the DB that you want to display
End If
End Sub
End Class
As you can see from the code, I want to display Title and DiaryContent in two separate textboxes by clicking on Title in the Combobox. This works fine.
The issue I have is DiaryDate only shows the first entry and does not update when selecting the Item from ComboBox.
Can anyone help?
You can try to play with ComboBox's SelectedItem property. Since ComboBox's DataSource is DataTable here, SelectedItem of ComboBox represent a row in DataTable. Given DataRow in hand, you can display value of any column of DataRow in TextBoxes :
........
If (Not Me.ComboBox1.SelectedItem Is Nothing) Then
Dim SelectedItem = TryCast(comboBox1.SelectedItem, DataRowView)
Me.TextBox1.Text = SelectedItem.Row("Title").ToString()
Me.TextBox2.Text = SelectedItem.Row("DiaryContent").ToString()
Me.TextBox3.Text = SelectedItem.Row("DiaryDate").ToString()
End If
........
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from Register"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
Dim id = reader.Item("cid")
ComboBox1.Items.Add(id)
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from register where cid ='" + ComboBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("cname")
TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub