Deleting a record from dataset and sql server - vb.net

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.

Related

OracleDataAdapter.Update cannot update database

Using Command As OracleCommand = conn.CreateCommand()
Command.CommandText = sSql
rsLFExcelRaw = New OracleDataAdapter(Command)
cbOracleCmdBuilder = New OracleCommandBuilder(rsLFExcelRaw)
dsLFExcelRaw = New DataSet()
rsLFExcelRaw.Fill(dsLFExcelRaw, "LF_EXCEL_RAW")
End Using
As stated above, I have a oraclecommand and oracledataadapter, I can retrieve data from database.
Then I update some value and add a new rows to the dataset, and do following:
dsLFExcelRaw.Tables(0).Rows.Add(row)
dsLFExcelRaw.AcceptChanges()
rsLFExcelRaw.Update(dsLFExcelRaw, "LF_EXCEL_RAW")
However, I cannot update the databse. Any ideas?
problem solved, after dsLFExcelRaw.AcceptChanges(), no change will be made.
So I change it to:
rsLFExcelRaw.Update(dsLFExcelRaw, "LF_EXCEL_RAW")
dsLFExcelRaw.AcceptChanges()

How to load data from an SQLite Database query into a textbox?

So I'm making a rota system for a project and I need a textbox to output the contracted hours of the employee that the user currently has selected in the combo box. The problem is, I have no idea how to go about it;
Sub GetContractedHours()
Dim sSql As String
Dim newds As New DataSet
Dim newdt As New DataTable
sSql = "SELECT emp_contractedhours FROM Employee WHERE emp_fn ='" & cboEmpName.Text & "%'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSql, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "Employee")
newdt = newds.Tables(0)
txtUserAlertHours.DataSource = newdt
con.Close()
End Sub
Please help! :)
You don't need any of that code. Just get all the data in the first place and then bind your ComboBox and your TextBox, e.g.
Dim table As New DataTable
Dim conection As New SQLiteConnection(ConnectionString)
Dim adapter As New SQLiteDataAdapter("SELECT emp_fn, emp_contractedhours FROM Employee", connection)
adapter.Fill(table)
cboEmpName.DisplayMember = "emp_fn"
cboEmpName.DataSource = table
txtUserAlertHours.DataBindings.Add("Text", table, "emp_contractedhours")
The TextBox will then be automatically populated when you make a selection in the ComboBox. That's how data-binding works.
If you do want to query the database each time then you shouldn't use a data adapter at all. You're only retrieving one value and that's exactly what ExecuteScalar is for. Create a command with the appropriate SQL, call ExecuteScalar and assign the result to the Text of your TextBox.
If you really did want to use data-binding with the code you have (which would be silly) then you can bind just as I have demonstrated above. Just note that, if you're going to use a different DataTable each time, you need to remove the old binding first. You can do that most easily by calling Clear on the DataBindings collection, assuming you have not bound any other properties.

Loading Data From Table1 then Save to Table2

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.

Visual Studio - multiple Table to multiple DataGridView with MS Access

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.

Write DataSet changed back to Access database

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.