No value given for one or more required parameters vb.net oledb - vb.net

Public Class ViewPhoneRecords
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim sqlquery As New OleDb.OleDbCommand
Dim con1 As New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database.accdb")
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim sqlupdate As String
' Here we use the UPDATE Statement to update the information. To be sure we are
' updating the right record we also use the WHERE clause to be sureno information
' is added or changed in the other records
sqlupdate = "UPDATE PhoneRecords SET Forename=#Forename, Surname=#Surname, Address=#Address, PhoneModel=#PhoneModel, PhoneNumber=#PhoneNumber, Postcode=#Postcode WHERE IDNum='" & IDTextBox.Text & "'"
Dim cmd As New OleDbCommand(sqlupdate, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.Add(New OleDbParameter("#Forename", ForenameTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Surname", SurnameTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Address", AddressTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#PhoneModel", PhoneModelTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#PhoneNumber", PhoneNumberTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Postcode", PostcodeTextBox1.Text))
con1.Open()
cmd.ExecuteNonQuery()
MsgBox("Row(s) Inserted !! ") 'Displays message box informing the user that the database has been added to
con1.Close() 'Connection closed
Me.Refresh()
End Sub
This is supposed to update a selected record in a datagrid view. However, when I click the 'Save changes' button, an error is given; "No value given for one or more parameters." Any idea how to solve this?

Use cmd.Parameters.AddWithValue instead of cmd.Parameters.Add

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

How to update access db by editing datagridview cells?

Im trying to edit items after inserting to access by clicking the save button? How can i save the edits done in datagridview rows to access?
Already tried the update query
For each loop
vb.net
Private Sub BunifuFlatButton1_Click(sender As Object, e As EventArgs) Handles BunifuFlatButton1.Click
Dim constring As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb")
Dim conn As New OleDbConnection(constring)
For Each row As DataGridViewRow In DataGridView1.Rows
Using con As New OleDbConnection(constring)
'nettxt.Text = (grosstxt.Text * perdistxt.Text / 100) - (dislctxt.Text + disusd.Text + distax.Text)
Dim cmd As New OleDbCommand("Update PurchaseInvoice set [Itemnum] = #ItemNum, [Itemname]= #ItemName, [Itemqty]= #ItemQty, [Itemprice] = #ItemPrice, [discount] =#discount, [subtotal] = #subtotal,[Preference] = " & preftxt.Text & ", [Suppnum] = " & pnumtxt.Text & ", [UniqueID] = " & pautotxt.Text & " Where [UniqueID] = " & pautotxt.Text & "", con)
cmd.Parameters.AddWithValue("#ItemID", row.Cells("ItemID").Value)
cmd.Parameters.AddWithValue("#ItemName", row.Cells("ItemName").Value)
cmd.Parameters.AddWithValue("#ItemQty", row.Cells("ItemQty").Value)
cmd.Parameters.AddWithValue("#ItemPrice", row.Cells("ItemPrice").Value)
cmd.Parameters.AddWithValue("#discount", row.Cells("discount").Value)
cmd.Parameters.AddWithValue("#subtotal", row.Cells("subtotal").Value)
cmd.Parameters.AddWithValue("#Ref", preftxt.Text.ToString)
cmd.Parameters.AddWithValue("#Suppnum", Convert.ToInt32(pnumtxt.Text))
cmd.Parameters.AddWithValue("#UniqueID", Convert.ToInt32(pautotxt.Text))
DataGridView1.AllowUserToAddRows = False
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
'This the code i used to show the data in datagridview:
Private Sub NewPurchaseInvoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb"
con.Open()
Dim sql As String = "Select [Itemnum],[Itemname],[Itemprice],[ItemQty],[discount],[subtotal] from PurchaseInvoice where [UniqueID] = " & pautotxt.Text & ""
Dim cmd10 As OleDbCommand = New OleDbCommand(Sql, con)
'Dim adap As New OleDbDataAdapter("Select [Itemnum],[Itemname],[Itemprice],[discount],[subtotal] from PurchaseInvoice where UniqueID = " & pautotxt.Text & "", con)
'Dim ds As New System.Data.DataSet
'adap.Fill(ds, "PurchaseInvoice")
Dim dr As OleDbDataReader = cmd10.ExecuteReader
Do While dr.Read()
DataGridView1.Rows.Add(dr("ItemNum"), dr("ItemName"), dr("ItemQty"), dr("ItemPrice"), dr("discount"), dr("subtotal"))
Loop
con.Close()
I expect that all the rows will be updated as each other, but the actual output is that each row has different qty name etc...
This code does not seem appropriate in the load event because pautotxt.Text will not have a value yet. Can you move it to a Button.Click?
I guessed that the datatype of ID is an Integer. You must first test if the the .Text property can be converted to an Integer. .TryParse does this. It returns a Boolean and fills IntID that was provided as the second parameter.
You can pass the connection string directly to the constructor of the connection. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. You can pass the Select statement and the connection directly to the constructor of the command.
ALWAYS use Parameters, never concatenate strings to avoid sql injection. Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
The DataAdapter will open the connection, fiil the DataTable and close the connection if it finds it closed; however if it is found open it will leave it open.
The last line binds the grid to the DataTable.
Private Sub FillGrid()
If Not Integer.TryParse(pautotxt.Text, IntID) Then
MessageBox.Show("Please enter a number")
Return
End If
dt = New DataTable()
Using con As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(Sql, con)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Dim adap = New OleDbDataAdapter(cmd)
adap.Fill(dt)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
DataTables are very clever. When bound to a DataGridView they keep track of changes and mark rows as update, insert, or delete. The DataAdapter uses this info to update the database. Once the database is updated we call .AcceptChanges on the DataTable to clear the marking on the rows.
Private Sub UpdateDatabase()
Using cn As New OleDbConnection(ConnString)
Using da As New OleDbDataAdapter(Sql, cn)
da.SelectCommand.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Using builder As New OleDbCommandBuilder(da)
da.Update(dt)
End Using
End Using
End Using
dt.AcceptChanges()
End Sub

Vb.net NO value given for one or more given parameters

Dim cmd As OleDbCommand = New OleDbCommand(Sql, con)
Dim strSql As String = "Select EmpName,Count(EmpName) from tblPO where OrderType='" &
"B2B" & "' and POExpireDate < #LogDate Group By EmpName"
Dim tstDate As DateTime = DateTime.Now
Dim dateAsString As String = tstDate.ToString("dd/MM/yy")
cmd.Parameters.AddWithValue("#LogDate", CType(dateAsString, String))
Dim dtb As New DataTable
Using dad As New OleDbDataAdapter(strSql, con)
dad.Fill(dtb)
End Using
con.Close()
I'm working in VB.NET
NO value given for one or more given parameters
error coming while filling datatable..why...how could I fix this.
pls help
Your problem is that you are passing your strSql and the connection to the data adapter but not the command which is what contains the parameter. Pass the command instead
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Using blocks ensure that your database objects are
'Closed And Disposed even if there Is an error.
Dim dtb As New DataTable
Using con As New OleDbConnection("Your connection string")
Dim strSql As String = "Select EmpName,Count(EmpName) from tblPO where OrderType = 'B2B' and POExpireDate < #LogDate Group By EmpName;"
Using cmd As OleDbCommand = New OleDbCommand(strSql, con)
cmd.Parameters.Add("#LogDate", OleDbType.Date).Value = DateTime.Now
'On the next line pass the command, no need to pass connection
'because it has already been passed to the constructor of the command
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtb)
End Using
End Using
End Using
End Sub

How do you stop and reset a form before it submits data to a database

I am making a login page and I have done the registration form, however, I need to validate the username. I have done the validating part, however, I can't seem to get it to not submit the data and reset the username box. This is the code
Imports System.Data.OleDb
Public Class Register
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub rB_Click(sender As Object, e As EventArgs) Handles rB.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Harry\Documents\Visual Studio 2015/users.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim usf As OleDbCommand = New OleDbCommand("SELECT * FROM [users] WHERE [username] = '" & uT.Text, myConnection)
Dim userFound As Boolean = True
If userFound = True Then
MsgBox("Username already found; Please choose another")
Dim frm = New Register
frm.Show()
Me.Close()
End If
Dim str As String
str = "insert into users ([username], [password], [Firstname], [LastName]) values (?, ?, ?, ?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(uT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(pT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("FirstName", CType(fnT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("LastName", CType(lnT.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
uT.Clear()
pT.Clear()
fnT.Clear()
lnT.Clear()
Me.Hide()
Form2.Show()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
First, please post your code instead of including an image as it's hard to reference back to when describing problems found.
That being said. You have a boolean UserFound that you are declaring and setting to True and then immediately checking to see if it's true. Of course it's going to be true, you just set it.
Also, I see nowhere in that image where you're even passing the query to get results back. (ie, executeReader, executeScalar)
Typically you can query the database and then check to see if any rows were returned or use executeScalar against a single column to see if a value was returned.

Creating new records in MSACCESS Table

I am attempting to create a new record from vb.net to an msaccess table, which i am able to do, but i have to add in the next consecutive ID number for it to actually save. For instance, if the next ID in the Access DB is 4, i have to type in 4 in the id textfield on my form. Code below:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sqlinsert As String
' We use the INSERT statement which tells our program to add the information
' from the Forms Text fields into the Databases columns.
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1, ID)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1, #ID)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("#ID", Convert.ToInt32(TextBox5.Text)))
' This is what actually writes our changes to the DataBase.
' You have to open the connection, execute the commands and
' then close connection.
con1.Open()
cmd.ExecuteNonQuery()
con1.Close()
' This are subs in Module1, to clear all the TextBoxes on the form
' and refresh the DataGridView on the MainForm to show our new records.
ClearTextBox(Me)
RefreshDGV()
Me.Close()
End Sub
How can i tell textbox5 which is the ID field, to be the next number in the access db?
Open your Access database, show the structure of your table and change the ID field type from numeric to AutoNumber.
Now your code don't need to pass anything to Access because the number will be handled automatically from Access.
You could just add these lines to your code to get back the number assigned by Access to your field
Dim sqlinsert As String
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
con1.Open()
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
cmd.CommandText = "SELECT ##IDENTITY"
Dim assignedID = Convert.ToInt32(cmd.ExecuteScalar())
' Eventually
TextBox5.Text = assignedID.ToString
con1.Close()
......
See also
How to retrieve last autoincremented value in MS-Access like ##Identity in Sql Server
Create a SELECT statement to retrieve the Max number form the table and add one to it. I do not know VB.Net, so it should be something like.
maxQry = "SELECT Max(IDColumnName) As MaxID FROM theTableName;"
Dim cmd As New OleDbCommand(maxQry, con1)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
TextBox5.Text = dr("MaxID").ToString
End While
End If
Unless the field is an AutoNumber type you do not have to worry about it at all.