I need to load data from Table 1. After loading it to a datagrid view, I have to save it to another table (Table2).
'' Load data
Dim cmdSQL As String = "SELECT * FROM Table1"
Dim ds_Tbl As New DataSet
Dim cmdBuilder As New SqlClient.SqlCommandBuilder
Dim da As New SqlClient.SqlDataAdapter(cmdSQL, connection)
cmdBuilder = New SqlCommandBuilder(da)
da.Fill(ds_Tbl, "Table2")
dgvTables.DataSource = ds_Tbl.Tables(0) '
'' Save data
Me.Validate()
da.Update(ds_Tbl.Tables("Table2"))
ds_Tbl.AcceptChanges()
I prefer to use command builder because this code is placed inside a loop for me to able to load various tables to one datagrid one at a time then save it to other designated table. Loading went okay but saving was unsuccessful. Please help.
Related
how can i populate multiple table into multiple DataGridview?
for example i have 3 tables which is table1, table2 and table3, and in my form i have 3 dataGridView with name of dataGridView1, dataGridView2 and dataGridView3. i found this solution Updating an Access Database via a DataGridView Using OLEDB in VB.NET as a result of my code.
function loadDatabaseDataToGridView
Dim msAccessFilePath As String
Dim con As New OleDbConnection
Dim dataTable, dataTable2, dataTable3, dataTable4 As New DataTable
Dim olebDataAdapter As New OleDbDataAdapter
Dim da As New OleDbDataAdapter
Dim dataSet As New DataSet
Private Sub loadDatabaseDataToGridView()
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & msAccessFilePath
dataSet.Tables.Add(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table1", con)
olebDataAdapter.Fill(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table2", con)
olebDataAdapter.Fill(dataTable2)
olebDataAdapter = New OleDbDataAdapter("Select * from table3", con)
olebDataAdapter.Fill(dataTable3)
DataGridView1.DataSource = dataTable.DefaultView
DataGridView2.DataSource = dataTable2.DefaultView
DataGridView3.DataSource = dataTable3.DefaultView
Dim cb = New OleDbCommandBuilder(olebDataAdapter)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
MessageBox.Show("Successfull")
Catch ex As Exception
MessageBox.Show("Failed")
con.Close()
End Try
con.Close()
End Sub
function SaveChanges
'Perform this on Button Save is Click
Private Sub saveChanges()
olebDataAdapter.Update(dataSet)
End Sub
This code is working as excpected, it is populating the data from MS Access file but when i clicked the button save to save the changes on edited data, an error has occurred.
THE ERROR:
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
anyone does know how to properly implement of what i am trying to achieve? Thank You Very Much!!!
Each DataAdapter object only has a single UpdateCommand, so you'll need one for each data table. If it runs the update command and no rows are updated (because the update command is actually for a table that you haven't changed) then you'll get the Concurrency Violatation.
It actually gets more complicated than this if your tables are related as the order that inserts, updates and deletions occur can be critical.
If you create a Strongly Typed Dataset it generates designer code that includes a TableAdapterManager class and all of the required data adapters. It might be worth playing around with this just so that you can see how the generated code works.
Just a note, the 'Concurrency violation' exception is actually there so that you can design an update command that will only succeed if the contents of the record in the database match the data held locally (to prevent you from overwriting another user's changes). Search for Optimistic Locking for more details.
I have the following code to alter the data, now I actually want to write said data back to the TESTS_TMP table in the Access database, how do I do that? I thought the adapter update did that but it doesn't?
Dim dataSet As DataSet = New DataSet
Using connection As New OleDbConnection(FileLocations.connectionStringNewDb)
connection.Open()
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("SELECT * FROM TESTS_TMP;", connection)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
adapter.Fill(dataSet)
'MsgBox(dataSet.Tables(0).Rows.Count)
'Code to modify the data in the DataSet here.
Dim id As Integer = 300
For i As Integer = 0 To dataSet.Tables(0).Rows.Count - 1
dataSet.Tables(0).Rows(i).Item(0) = id
id = id + 1
Next
' Without the OleDbCommandBuilder this line would fail.
'builder.GetUpdateCommand()
'adapter.Update(dataSet)
Try
adapter.Update(dataSet.Tables(0))
dataSet.AcceptChanges()
Catch x As Exception
' Error during Update, add code to locate error, reconcile
' and try to update again.
End Try
End Using
MsgBox(dataSet.Tables(0).Rows(1).Item(0))
You're calling AcceptChanges. and it is marking all of the rows as being unmodified, so they are never updated in the database. Remove this call.
I want to change a datagridview column 'TeamAssignment' which loads from the database to have dropdowns (which is also populated from the database)
Dim conn As New SqlConnection(My.Resources.FCLRptConn)
Dim cmd As New SqlCommand("spFCLLUVTeamAssignment", conn)
Dim da As New SqlDataAdapter(cmd)
Dim TeamAssign As New DataSet
da.Fill(TeamAssign)
teamComBo.HeaderText = "Team Assignment"
teamComBo.DataPropertyName = "TeamAssignment"
teamComBo.DataSource = TeamAssign.Tables(0)
teamComBo.DisplayMember = "FCLTeamName"
teamComBo.ValueMember = "FCLTeamID"
dgvAgentAssignment.Columns.RemoveAt(5)
dgvAgentAssignment.Columns.Insert(5, teamComBo)
This is what I have used but I get an error that says that a column exists. How would I keep my existing column without having to remove it but populate it with the dropdowns?
Thanks
Once again i am turning to you for help. I am a little stuck when trying to save data entered in a DataGridView back to the SQL table.
I have followed a number of posts but just cant seam to figure it out
I declare the following variables globally on the form
Dim SQLAdaptor As New SqlClient.SqlDataAdapter
Dim Con As New SqlClient.SqlConnection
Dim builder As SqlClient.SqlCommandBuilder
I call this when the form loads
Private Sub SetTicketList()
Con.ConnectionString = CropTrackMod.strConn
SQLAdaptor.SelectCommand = New SqlClient.SqlCommand("SELECT StockRef, Weight, EstimatedPrice, EstimatedPrice, DespatchedQuantity, EstimatedTransport, EstimatedLineTotal FROM TicketDetail", Con)
builder = New SqlClient.SqlCommandBuilder(SQLAdaptor)
Con.Open()
Dim myTable As DataTable = New DataTable
SQLAdaptor.Fill(myTable)
dgvTicketDetail.DataSource = myTable
End Sub
I call this when the user leaves a row on the data grid view which should save back to the sql table
Private Sub dgvTicketDetail_RowLeave
' at grid save'
Dim myTable = CType(dgvTicketDetail.DataSource, DataTable)
SQLAdaptor.Update(myTable)
End Sub
When the form is loaded the data grid view is populated with the correct columns so i think that the first part is ok. The problem comes when saving the data back. When I run it the first time there is no error message. When I try a second row I get the following error:
Update requires a valid InsertCommand when passed DataRow collection with new rows.
From what I can figure the problem is generated because there is no update command set on the data adaptor.
I am trying to delete a record from a DataTable and then update the database that it is attached to.
I delete a row of my DataGridView and then update my Dataset using:
Me.Tab2_DGVDuty.Rows.RemoveAt(Me.Tab2_DGVDuty.CurrentRow.Index)
ds1.AcceptChanges()
Tab2_DGVDuty.Refresh()
I then call my adapter.update as below:
Dim adapter As New SqlDataAdapter
Dim cmdBuilder As New SqlCommandBuilder(adapter)
Dim DutyDetails As String = "SELECT * from MyTable"
adapter.SelectCommand = New SqlCommand(DutyDetails, SQLConn)
adapter.UpdateCommand = cmdBuilder.GetUpdateCommand
adapter.DeleteCommand = cmdBuilder.GetDeleteCommand
Dim cb As SqlCommandBuilder = New SqlCommandBuilder(adapter)
adapter.Update(ds1.Tables("DT_Table"))
But when i reload the data my record is still there. If I change a value and update this works fine but for some reason the delete doesnt.
Any help much appreciated.
EDIT:
OK I changed my delete to the following as suggested below:
ds1.Tables("DT_Table").Rows(Tab2_DGVDuty.CurrentRow.Index).Delete()
This is attached to a button, it deletes fine the first time but on the second press to delete another record nothing happens. If I use
ds1.AcceptChanges()
then it works fine. However, if i use the above then my code below does not delete anything from the database:
Dim adapter As New SqlDataAdapter
Dim cmdBuilder As New SqlCommandBuilder(adapter)
Dim DutyDetails As String = "SELECT * from MyTable"
adapter.SelectCommand = New SqlCommand(DutyDetails, SQLConn)
adapter.UpdateCommand = cmdBuilder.GetUpdateCommand
adapter.DeleteCommand = cmdBuilder.GetDeleteCommand
Dim cb As SqlCommandBuilder = New SqlCommandBuilder(adapter)
adapter.Update(ds1.Tables("DT_Table"))
You don't want to remove the DataRow from the DataTable, you want to Delete it
ds1.Tables("DT_Table").Rows(Tab2_DGVDuty.CurrentRow.Index).Delete()
Don't call ds1.AcceptChanges() afterwards since the Update will not recognize that this row has changed anymore then because it will change it's RowState to Unchanged. DataAdapter.Update calls AcceptChanges as the last step implicitely, not you.
I assume that Tab2_DGVDuty is a DataGridView and not the DataTable, i've taken that into account above.