invalid operation exception was unhandled Update requires a valid UpdateCommand - vb.net

From these codes, I want to edit, add and save data from VB to MS Access permanently. I created dozens of Visual Basic projects but no progress at all.
Public Class Form1
Private Sub ProductDescBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProductDescBindingNavigatorSaveItem.Click
Me.Validate()
Me.ProductDescBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.INVSYSDataSet)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'INVSYSDataSet.ProductDesc' table. You can move, or remove it, as needed.
Me.ProductDescTableAdapter.Fill(Me.INVSYSDataSet.ProductDesc)
End Sub
End Class
The problem is that "invalid operation exception was unhandled" appears, Update requires a valid UpdateCommand from code Me.TableAdapterManager.UpdateAll(Me.INVSYSDataSet)
If you need the DataSource, I can provide code from another VB project.
*updated second code, help for sql please
*updated srry bout that
Public Class Add_Products
Private myConString As String
Private con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Private Dadapter As OleDb.OleDbDataAdapter
Private DSet As DataSet
Private DSet2 As DataSet
Private ConCMD As OleDb.OleDbCommand
Dim strSql As String
Dim inc As Integer
Dim MaxRows As Integer
Private Sub Add_Products_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\larca\Documents\Visual Studio 2010\Projects\march16\march16\obj\x86\Debug\INVSYS.mdb"
con.ConnectionString = myConString
con.Open()
Dadapter = New OleDb.OleDbDataAdapter("select * from ProductDesc", con)
DSet = New DataSet
Dadapter.Fill(DSet, "ProductDesc")
DataGridView1.DataSource = DSet.Tables("ProductDesc")
con.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using con = New OleDb.OleDbConnection(myConString)
con.Open()
Dim cmd As OleDb.OleDbCommand
cmd = New OleDb.OleDbCommand("UPDATE ProductDesc", con)
Dadapter.UpdateCommand = cmd
Dadapter.Update(DSet, "ProductDesc")
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

The error message is telling you that you have not defined an Update command for the DataAdapter. From DbDataAdapter.Update Method DataSet, String: If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception.
To resolve this, assign the UpdateCommand an OleDbCommand object with your update logic, like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using con = New OleDb.OleDbConnection(myConString)
con.Open()
Dim cmd As OleDbCommand
cmd = New OleDbCommand("<your update SQL goes here>", con)
DAdapter.UpdateCommand = cmd
Dadapter.Update(DSet, "ProductDesc")
End Using
End Sub
Simply put your SQL in the OleDbCommand and assign it to the UpdateCommand property.
Look at this link for a detailed example (and be sure to use parameterized queries like in the example to avoid SQL Injection attacks): OleDbDataAdapter.UpdateCommand Property

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

GETTING ERROR when updating database in vb.NeT

I'M Creating A Database updater using vb.NET and database AS DATABASE1.SDF. I I WANTED TO Update the DATABASE IN DATAGridview dynamically. For UPDATING SQL COMMAND i'm USING A SQLCECOMMANDBUILDER BUT I'M GETTING A ERROR THERE AS "The DataAdapter.SelectCommand property needs to be initialized."
HERE IS MY CODE:
Imports System.Data.OleDb
Imports System.Data
Imports System.Data.SqlServerCe
Public Class Admin
Dim update As New SqlCeDataAdapter
' sql connection strings
Dim SQLCon As String = "Data Source=Database1.sdf"
Dim sqlstr As String = "Select * from Base_Plate "
Dim sqlstr1 As String = "Select * from Alloy "
Dim sqlstr2 As String = "Select * from Bead_Factor "
Dim sqlstr3 As String = "Select * from Difficulty_Factor "
Dim sqlstr4 As String = "Select * from Price_Factor "
' sql variable of base
Dim adapter As New SqlCeDataAdapter(sqlstr, SQLCon)
Dim ds As New DataSet()
' sql variable of alloy
Dim adapter1 As New SqlCeDataAdapter(sqlstr1, SQLCon)
Dim ds1 As New DataSet()
' sql variable of bead
Dim adapter2 As New SqlCeDataAdapter(sqlstr2, SQLCon)
Dim ds2 As New DataSet()
'sql variable of difficulty
Dim adapter3 As New SqlCeDataAdapter(sqlstr3, SQLCon)
Dim ds3 As New DataSet()
'sql variable of price
Dim adapter4 As New SqlCeDataAdapter(sqlstr4, SQLCon)
Dim ds4 As New DataSet()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
update.Update(ds)
LoadGrid()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Visible = False
LoginForm1.Visible = True
End Sub
Private Sub Admin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadGrid()
Button2.Enabled = False
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
End Sub
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
Button2.Enabled = True
End Sub
Private Sub LoadGrid()
'************** base datagrid ********************
adapter.Fill(ds, "Base_Plate")
DataGridView1.DataSource = ds.Tables(0)
DataGridView1.Rows(0).Selected = True
'***************** alloy datagrid *********************
adapter1.Fill(ds1, "Alloy")
DataGridView2.DataSource = ds1.Tables(0)
DataGridView2.Rows(0).Selected = True
'***************** bead datagrid *********************
adapter2.Fill(ds2, "Bead_Factor")
DataGridView3.DataSource = ds2.Tables(0)
DataGridView3.Rows(0).Selected = True
'***************** difficulty datagrid *********************
adapter3.Fill(ds3, "Difficulty_Factor")
DataGridView4.DataSource = ds3.Tables(0)
DataGridView4.Rows(0).Selected = True
'***************** Price datagrid *********************
adapter4.Fill(ds4, "Price_Factor")
DataGridView5.DataSource = ds4.Tables(0)
DataGridView5.Rows(0).Selected = True
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
End Sub
You're doing it wrong. Firstly, as the error message states, you haven't set the SelectCommand of the data adapter that you're passing to the command builder constructor. Here's the relevant snippets from your code:
Dim update As New SqlCeDataAdapter
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
As you can see, nowhere do you provide a SQL SELECT statement so how is the command builder supposed to know how to build the other commands?
Secondly, even if the adapter was properly configured, this is wrong:
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
You DO NOT have to get the commands from the command builder and assign them to the properties of the data adapter. The only reason to do that is if you want to edit them, which you do not. The proper way to create a command builder is on the line immediately after you create the data adapter, e.g.
Dim myDataAdapter As New SqlCeDataAdapter(query, myConnection)
Dim myCommandBuilder As New SqlCeCommandBuilder(myDataAdapter)
That's it. You create it once and once only and then the data adapter will just work when you call Update. There's no creating a new one each time you save and there's no getting and assigning of commands.

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.

SQL connection error showing INVALID OBJECT NAME

I have done follwing coding but it shows error
Invalid object name 'sanket'
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim str As String
Private Sub ConnectToSQL()
Try
con.ConnectionString = "Data Source=SA_N_KET-PC\SQLEXPRESS;Initial Catalog=repeat;Integrated Security=true;"
con.Open()
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
'DoNothing.
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CryrptDataSet.sanket' table. You can move, or remove it, as needed.
Me.SanketTableAdapter.Fill(Me.CryrptDataSet.sanket)
ConnectToSQL()
End Sub
Public Sub exe()
str = "insert into sanket(n)values ('" & TextBox1.Text & "')"
da = New SqlDataAdapter(Str, con)
da.Fill(ds, "sanket")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
exe()
End Sub
End Class

about update data on datagridview and filter

i'm getting confuse about dataset and dataview, which i either use dataset to update data or dataview to filter data, but cannot have both together at the same time.
Private Sub searchStaff_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ds = New DataSet
dv = New DataView
Dim ad As New SqlDataAdapter("SELECT * FROM staff", connection)
ad.Fill(ds, "staff")
dv.Table = ds.Tables("staff")
Me.DataGridView1.DataSource = dv
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Try
dv.RowFilter = "StaffName like '" & txtSearch.Text & "*'"
Catch ex As Exception
End Try
End Sub
this is the code of filtering data on dataview,which work fine for me.
but later on, i have to implement another function of update data on datagridview, what i found on internet require me to use dataset as datasource rather than dataview.
Private Sub searchStaff_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
connection = New SqlConnection(connectionString)
ds = New DataSet
cmd = New SqlCommand("SELECT * FROM staff", connection)
adp=New SqlDataAdapter(cmd)
adp.Fill(ds, "staff")
Me.DataGridView1.DataSource = ds
Me.DataGridView1.DataMember = "staff"
End Sub
Private Sub btnUpdate_ClickEvent(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.ClickEvent
Dim cmdbuilder As New SqlCommandBuilder(adp)
Dim i As Integer
Try
i = adp.Update(ds, "staff")
MsgBox("Record updated= " & i)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
so i hope some 1 can show me, how to i can have both functions"update,filter" at the same time by using what datasource?
You must use DataSet (or DataTable) with SqlDataAdapter for make an Update operation; DataView is used for filter data but not to commit changes to database. Here an example for your searchStaff_Load method:
Private Sub searchStaff_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
connection = New SqlConnection(connectionString)
ds = New DataSet
cmd = New SqlCommand("SELECT * FROM staff", connection)
adp=New SqlDataAdapter(cmd)
adp.Fill(ds, "staff")
Me.DataGridView1.DataSource = ds.Tables("staff").DefaultView 'Assign DataView to grid
'Me.DataGridView1.DataMember = "staff" 'No need when using DataView
End Sub
The txtSearch_TextChanged and btnUpdate_ClickEvent are already correct. The first filter using DataView, the second update database using DataSet.