No Value Given for one or more required parameters - vb.net

I'm trying to get this update command to work. I have a table in access that has two fields, and I'm just trying to update the second one. I have code like this already in my program and it worked - I can't figure out why this code doesn't work:
Private Sub Button9_Click(sender As System.Object, e As System.EventArgs) Handles Button9.Click
Try
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BuddyMatching.accdb;Persist Security Info=False")
Dim cmd1 As New OleDb.OleDbCommand("Update Priorities set priorityDesc = '" & ComboBox12.Text & "' where priorityNum =1", conn)
Dim cmd2 As New OleDb.OleDbCommand("Update Priorities set priorityDesc = '" & ComboBox13.Text & "' where priorityNum =2", conn)
Dim cmd3 As New OleDb.OleDbCommand("Update Priorities set priorityDesc = '" & ComboBox14.Text & "' where priorityNum =3", conn)
conn.Open()
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
cmd3.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Every time I run this code, I get "No value given for one or more required parameters" returned via the MsgBox. My ComboBoxes are not inputting null values, so that's not it. Hopefully another set of eyes will spot the issue.
Thanks!

Related

How to restrict user to not update the date and the week textbox

My question is "The user should be able to update (edit) a previously entered log but the date and the week number should be prevented from being edited"
How do I restrict user to not update the date and the week textbox?
Here is my current update code:
Private Sub Btnupdatelog_Click(sender As Object, e As EventArgs) Handles Btnupdatelog.Click
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
cmd = New SqlCommand("update Logbook Objectives='" & Txtobjectives.Text & "',Contents='" & Txtcontent.Text & "',Company_Signature_Stamp='" & Txtsignature.Text & "',Company_Date='" & DateTimePicker2.Text & "' where LogId=" & TxtLogId.Text & "", conn)
conn.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alex\source\repos\CurriculumVitae(CV)\bin\Debug\CurriculumVitae(CV).mdf;Integrated Security=True;Connect Timeout=30"
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
MsgBox("Update Successfully")
End Sub
End Class
To prevent certain fields from being update, simply don't include those fields in the command text. I removed the date field from the text.
Database objects need to be closed and disposed. Using...End Using blocks handle this for you even if there is an error. In this code, both the connection and command are included in the Using block. Note the comma at the end of the first line of the Using.
Never concatenate strings to build sql text. Always use parameters to avoid sql injection. I had to guess at the datatype and size of your fields. Check your database for the correct values.
Private Sub Btnupdatelog_Click(sender As Object, e As EventArgs) Handles Btnupdatelog.Click
Using conn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alex\source\repos\CurriculumVitae(CV)\bin\Debug\CurriculumVitae(CV).mdf;Integrated Security=True;Connect Timeout=30"),
cmd As New SqlCommand("update Logbook Set Objectives= #Objectives, Contents= #Contents, Company_Signature_Stamp= #Signature where LogId= #ID;", conn)
With cmd.Parameters
.Add("#Objectives", SqlDbType.VarChar, 300).Value = Txtobjectives.Text
.Add("#Contents", SqlDbType.VarChar, 300).Value = Txtcontent.Text
.Add("#Signature", SqlDbType.VarChar, 100).Value = Txtsignature.Text
.Add("#ID", SqlDbType.Int).Value = CInt(TxtLogId.Text)
End With
conn.Open()
cmd.ExecuteNonQuery()
End Using
MsgBox("Update Successfully")
End Sub

Syntax Error near Insert Statement

I am trying to insert data in Access database but getting a Syntax error exception :( What am I doing wrong ?
Private Sub savebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles savebtn.Click
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\vb8\Mini-project\Mini-project\mini_db.mdb")
Dim query As String
Try
con.Open()
query = "INSERT INTO minitab VALUES (" & TextBox1.Text & "," & TextBox2.Text & ",#dob ," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox7.Text & "," & TextBox8.Text & "," & TextBox9.Text & ")"
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(query, con)
Dim dt As New DataTable
da.Fill(dt)
MsgBox("Data has been saved", MsgBoxStyle.SystemModal, "ok")
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
You are adding values in your Insert statement without addressing the columns. Now, this is not necessary if you put the values in the correct order so I suggest you to check it again. However, if you specify the column names then your insert statement might look like:
"INSERT INTO minitab(column1,Column2,Column3)VALUES(#col1,#col2,#col3)",connectiontring
cmd.Parameters.Add("#col1",OleDbType.VarChar).Value = TxtBox1.Text 'make sure to set the datatype correctly
cmd.Parameters.Add("#col2",OleDbType.VarChar).Value = TxtBox2.Text
.........
cmd.ExecuteNonQuery
And most importantly, what are you trying to do? If you are trying to insert data, then why are you using a DataTable? The code above will let you insert data into the database. However, a datatable is used to get data from the database and display it. Also DataTables have change tracking and are used in conjunction with DataAdapters to perform CRUD operations.
However, to use a DataTable to display data, you can try this:
Dim cmd as new OleDbCommand("Select * from minitab",connectionstring)
Dim dt as new DataTable
Dim ada as new OleDbDataAdapter(cmd)
ada.Fill(dt)
To display the data, you can use various controls. One of them is a DataGridView.
DataGridView1.DataSource = dt
Hope you understand :)

What's wrong with this SQL Insert statement of mine?

I am trying to add a record to my table, however I'm getting an exception after it attempts to do so. I am able to open the connection successfully, (my first messagebox shows up) but after that I get the exception. Here's my code:
Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con = New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;")
Try
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (txtFirstName.Text, txtLastName.Text)"
cmd.Connection = con
con.Open()
MsgBox("Connection Open ! ")
cmd.ExecuteNonQuery()
MsgBox("Record inserted")
con.Close()
Catch ex As Exception
MsgBox("Error!")
End Try
End Sub
For future readers - Sql parameters will save a lot of your and your coworkers time.
Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim connString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;"
Using connection As New SqlConnection(connString)
Using command As New SqlCommand(connection)
command.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (#FirstName, #Lastname)"
Dim params As SqlParameter() =
{
New SqlParameter With { .ParameterName = "#FirstName", .SqlDbType.VarChar, .Value = txtFirstName.Text },
New SqlParameter With { .ParameterName = "#LastName", .SqlDbType.VarChar, .Value = txtLastName.Text },
}
command.Parameters.AddRange(params)
connection.Open()
command.ExecuteNonQuery()
' Inserted
End Using
End Using
End Sub
Same for try.. catch(as #Plutonix has noticed in the comments) - if you will get "real" exception you will find reason and solution much faster
You need to look at the exception message (ex.Message) see what the issue is...If you have an error similar to multipart identifier then try this query string instead of your current query string for a quick test.
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES ('" & txtFirstName.Text & "', '" & txtLastName.Text & "')"
Check out parameterized query as previously indicated

Vb.net db issue

I'm writing a calorie counter tool for my girlfriend...
But I've run in to an issue I really cant figure out...
I have place in my script where I would wanna take some information out from my db...
The specific place in the script thats teasing, is the one that will take out data from a row called "antal" from a table called "items".
One place in my script, I call "navn" from items, and it works perfect...
This other place, it gives me the error that there isn't any data in the row!
My code looks so far like this:
Imports System.Data.OleDb
Private Sub ins_kat_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ins_kat.SelectedIndexChanged
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Privat\MCC\mccdb.mdb")
Con.Open()
Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM items WHERE kat = '" & ins_kat.Text & "' ORDER BY id DESC", Con)
Dim read As OleDbDataReader = command.ExecuteReader()
ins_mad.Items.Clear()
While read.Read()
ins_mad.Items.Add(read.Item("navn")) '<---- This place works!!!
End While
Con.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim ialt_c_counter As String
Dim ialt_c_counter_conv As Decimal
Dim ialt_c_counter_conv2 As Decimal
Dim ialt_counter As String
Dim ialt_final As Decimal
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Privat\MCC\mccdb.mdb")
Con.Open()
Dim command1 As OleDbCommand = New OleDbCommand("SELECT * FROM food WHERE dag = '" & stat_dag.Text & "' AND maaned = '" & stat_maaned1.Text & "' AND aar = '" & stat_aar1.Text & "'", Con)
Dim read1 As OleDbDataReader = command1.ExecuteReader()
While read1.Read()
ialt_c_counter = read1.Item("antal")
ialt_c_counter_conv = System.Convert.ToDecimal(ialt_c_counter)
Dim commandX As OleDbCommand = New OleDbCommand("SELECT * FROM items", Con)
Dim reader As OleDbDataReader = commandX.ExecuteReader()
ialt_counter = reader.Item("antal") '<--- THIS ONE is giving me the error!!
ialt_c_counter_conv2 = System.Convert.ToDecimal(ialt_counter)
ialt_final = (ialt_c_counter_conv / 100 * ialt_c_counter_conv2) + ialt_final
End While
Con.Close()
MsgBox(ialt_final)
End Sub
End Class
By now, I want a MsgBox telling me the result of my algorithm, but I don't even get that far cause of the error message...
I guess the error you see is
InvalidOperationException: Invalid attempt to read when no data is present.
You never call Read() on the OleDbDataReader called reader.
Note how you use a While loop to call Read() for read and read1, but not reader (bad variable names, btw).

OleDBException 0x80040e10 No value Given

The first part of this works correctly, when the Textbox value is null. It throws an exception however, when i try to filter search using the second part of the if statement.
The reason the table var is set that way is because the user has the option to load different tables.
The textbox string is the search parameter.
Public Class form1
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= .\Service.accdb ;")
Dim da As New OleDbDataAdapter
Private Sub getdata()
Me.Refresh()
Dim dt As New DataTable
Dim cmd As New OleDbCommand
Dim table As String = ComboBox1.Text.ToString
Dim txt As String = TextBox1.Text.ToString
If TextBox1.Text = Nothing Then
con.Open()
da.SelectCommand = New OleDbCommand("select * from [" & table & "] ;", con)
con.Close()
Else
con.Open()
da.SelectCommand = New OleDbCommand("select * from [" & table & "] where (External like '%" & txt & "%' or Internal like '%" & txt & "%' or Code like '%" & txt & "%');", con)
con.Close()
End If
Try
da.Fill(dt)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
DataGridView1.DataSource = dt
End Sub
End Class
Any help would be appreciated.
EDIT
It seems that this bit of code is stopping it from searching correctly, however without it i cannot save to the DB..
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
So i am assuming i am missing a paramter from this section?