VB.NET 2010 ADD STATEMENT - vb.net

i have this code on my ADD button, is there's other way to shorten this statement of code.
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
On Error GoTo ErrSQL
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
'Open connection if it is not yet open
cnn.Open()
End If
cmd.Connection = cnn
'check whether add new update
If Me.txtstdID.Tag & "" = "" Then
'add new
'add data to table
cmd.CommandText = "INSERT INTO inventory (ID,BRAND,SPECIFICATION,STATUS) Values ('" & Me.txtstdID.Text & "','" & Me.cboBrand.Text & "','" & Me.txtDescription.Text & "','" & strStat & "')"
cmd.ExecuteNonQuery()
Else
'update data in table
cmd.CommandText = "UPDATE inventory SET ID =" & Me.txtstdID.Text & ",BRAND='" & Me.cboBrand.Text & "', SPECIFICATION='" & Me.txtDescription.Text & "', STATUS = '" & strStat & "', WHERE ID=" & Me.txtstdID.Text & ""
cmd.ExecuteNonQuery()
End If
'refresh data in list
RefreshData()
'clear form
Me.btnClear.PerformClick()
'close connection
cnn.Close()
Exit Sub
ErrSQL:
MsgBox(Err.Description)
End Sub

There isn't too much to do to shorten the code, there is a lot to do to prevent Sql Injection and parsing problems.
I will try to change your code to this
Try
Using cnn = new OleDbConnection(constring)
Dim cmd As New OleDb.OleDbCommand
cnn.Open()
cmd.Connection = cnn
Dim cmdText as String
'check whether add new update
If Me.txtstdID.Tag & "" = "" Then
cmdText = "INSERT INTO inventory (ID,BRAND,SPECIFICATION,STATUS) " +
"Values (#ID, #Brand, #specs, #stat)"
else
cmdText = "UPDATE inventory SET ID=#ID, BRAND=#Brand,SPECIFICATION=#specs" +
"STATUS = #stat WHERE ID=#ID"
End If
cmd.CommandText = cmdText
cmd.Parametes.AddWithValue("#ID", Me.txtstdID.Text)
cmd.Parametes.AddWithValue("#Brand", Me.cboBrand.Text)
cmd.Parametes.AddWithValue("#specs", Me.txtDescription.Text)
cmd.Parametes.AddWithValue("#stat", strStat)
cmd.ExecuteNonQuery()
End Using
'refresh data in list
RefreshData()
'clear form
Me.btnClear.PerformClick()
Catch(x As Exception)
MsgBox(x.Message)
End Try
I was tempted to remove the redundant SET ID=#ID in the Update statement, but, then you have to add the #ID parameter after the other parameters because in OleDb the parameter order matters

Related

Shows Error Conversion from String to type Double is not Valid, Input String is not in correct Format

Following are my codes Pls Help me
I found this error on updating the Table
Private Sub UpdateInventory()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("MainConString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim Query1 As String
Try
Dim Result As DialogResult
Result = MessageBox.Show(" Update this Record ?", "Save ! ", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If Result = DialogResult.Yes Then
For J As Integer = 0 To DataGridStock.Rows.Count - 1 Step +1
Query1 = "Update Tempstock Set Type='" & LabelTrancode.Text & "', Prefix='" & Lblprefix.Text & "', Srl='" & TextINVNo.Text & "',
DOcDate='" & TextBoxdocdate.Text & "',Sno='" & DataGridStock.Rows(J).Cells(0).Value & "', Hsncode='" & DataGridStock.Rows(J).Cells(4).Value & "',
Branch='" & LBLBranchcode.Text & "',Taxcode='" & DataGridStock.Rows(J).Cells(5).Value & "',Code='" & DataGridStock.Rows(J).Cells(2).Value & "',
Qty='" + (DataGridStock.Rows(J).Cells(6).Value) + "',Rate='" + Int(DataGridStock.Rows(J).Cells(8).Value) + "',Unit='" & DataGridStock.Rows(J).Cells(7).Value & "'"
Dim query = String.Concat(Query1, ";")
con.Open()
cmd = New SqlCommand(query, con)
reader = cmd.ExecuteReader
reader.Close()
con.Close()
Next
MessageBox.Show(" Stock Updated")
End If
Catch ex As Exception
End Try
End Sub

trying to update a passowrd and username in database i get operator error

Imports System.Data.OleDb
Imports System.Data
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ran As New Random
TextBox2.Text = ran.Next(1, 8)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Or MaskedTextBox3.Text = "" Then
MsgBox("Please fill all text boxes With the required info")
Else
Dim cmd As OleDbCommand
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\users\nikh8610\Documents\users.accdb")
Dim str As String
con.Open()
str = "UPDATE users SET username = '" & TextBox1.Text & "'WHERE (ID = '" & TextBox2.Text & "') AND password='" & MaskedTextBox3.Text & "' WHERE (ID = '" & TextBox2.Text & "')"
cmd = New OleDbCommand(str, con)
cmd.ExecuteNonQuery()
con.Close()
End If
End Sub
End Class
Your query isn't valid. You are using two WHERE parts on the query. Try the following:
str = "UPDATE users SET username = '" & TextBox1.Text & "' WHERE ID = '" & TextBox2.Text & "' AND password='" & MaskedTextBox3.Text & "'"
You also don't UPDATE the password of the user. You can use something like the following to UPDATE the username and password.
str = "UPDATE users SET username = '" & txtUsername.Text & "', password = '" & txtNewPassword.Text & "' WHERE ID = '" & txtUserID.Text & "' AND password = '" & txtOldPassword.Text & "'"
You should also use prepared statements to UPDATE the user information:
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "UPDATE users SET username = ?, password = ? WHERE ID = ? AND password = ?"
cmd.Parameters.Add("NewUsername", OleDbType.VarWChar, 50)
cmd.Parameters.Add("NewPassword", OleDbType.VarWChar, 50)
cmd.Parameters.Add("UserID", OleDbType.Long)
cmd.Parameters.Add("OldPassword", OleDbType.VarWChar, 50)
cmd.Parameters(0).Value = txtNewUsername.Text
cmd.Parameters(1).Value = txtNewPassword.Text
cmd.Parameters(2).Value = txtUserID.Text
cmd.Parameters(3).Value = txtOldPassword.Text
cmd.Prepare()
cmd.ExecuteNonQuery()

Visual Basic 2013 create new Record in Access Execure Error

I am creating a simple UserID/Password access database for a Visual Basic program.
Everything works except adding a new user.
My text box Objects are linked to my database but I keep getting this error when I try to add my new user.
Error: An unhandled exception of type
'System.Data.OleDb.OleDbException' occurred in System.Data.dll
HERE IS MY CODE:
Imports System.Data.OleDb
Public Class newUser
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PasswordCheck.accdb"
Dim conn As OleDbConnection = New OleDbConnection
Private Sub btnNewUser_Click(sender As Object, e As EventArgs) Handles btnNewUser.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PasswordCheck.accdb"
Dim conn As OleDbConnection = New OleDbConnection
conn.ConnectionString = connString
conn.Open()
Dim SaveNew As String = "INSERT INTO [Password] (UserId, Password, firstName, LastName) Values ('" & txtUserID.Text & "','" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
Dim cmd As New OleDbCommand
cmd.Connection = conn
With cmd
.CommandText = SaveNew
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("You have been added to our Database")
txtUserID.Text = ""
txtPassword.Text = ""
txtFirst.Text = ""
txtLast.Text = ""
conn.Close()
End Sub
Private Function SaveNew() As String
Throw New NotImplementedException
End Function
End Class
Password is a reserved word also for a field, so:
Dim SaveNew As String = "INSERT INTO [Password] (UserId, [Password], FirstName, LastName) Values ('" & txtUserID.Text & "','" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
And further, if UserID not is text, then no quotes:
Dim SaveNew As String = "INSERT INTO [Password] (UserId, [Password], FirstName, LastName) Values (" & txtUserID.Text & ",'" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
That said, try to explorer how to carry this out using parameters. Much more fun than SQL concatenation.

no value given for one or more required parameters in updating deleting records

I cant figure out whats wrong with this,when i update a record from my list view a pop up appears saying no value given for one or more required parameters.
heres my code:
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles BtnUpdate.Click
Try
Dim SqlQuery As String = "UPDATE UsersTable Set AccountType = '" & CmbAccountType.Text & "' , Username = '" & TxtUsername.Text & "' , UserPassword = '" & TxtPassword.Text & "' , Firstname = '" & TxtFirstname.Text & "' , Lastname = '" & TxtLastname.Text & "' , Sex = '" & CmbSex.Text & "',Birthdate = '" & DateTimePickerBirthdate.Text & "' , ContactNumber = '" & TxtContact.Text & "' , Address = '" & TxtAddress.Text & "' WHERE UserID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Conn
.ExecuteNonQuery()
End With
MsgBox("Account successfully updated!")
loadlistview()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles BtnDelete.Click
Try
Dim SqlQuery As String = "DELETE FROM ProductTable WHERE UserID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Conn
.ExecuteNonQuery()
End With
MsgBox("Account deleted.")
loadlistview()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The problem is in the WHERE condition which you used in your query. so you can correct it by using the following query
In update query :
Dim SqlQuery As String = "UPDATE UsersTable Set AccountType = '" & CmbAccountType.Text & "'....................." & _
"WHERE UserID = '" & id & "';" '<----- you miss a single quote in where clause.
In Delete query :
Dim SqlQuery As String = "DELETE FROM ProductTable WHERE UserID = '" & id & "';"

Saving CheckBox Items to Database Access

i have vb.net application form.
It contains ID, Age,Name as Textbox and TC as Checkbox.
I have following code to these items, but checkbox items is saved automatically whether checked or not.
So what to do?
[Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim con_str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Satyam\Documents\Database2.accdb"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = con_str
con.Open()
'MsgBox(con.State)
Dim myReader As OleDbDataReader
cmd = New OleDbCommand("select * from Table1", con)
myReader = cmd.ExecuteReader
While myReader.Read()
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub AddTable1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddTable1.Click
Try
con.ConnectionString = con_str
con.Open()
'MsgBox(con.State)
cmd = New OleDbCommand("insert into Table1(ID,Age,Name,TC) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','" & Nametxt.Text & "','" & TCtxt.Text & "')", con)
cmd.ExecuteNonQuery()
MsgBox("Added Successfuly")
Dim myReader As OleDbDataReader
cmd = New OleDbCommand("select * from Table1", con)
myReader = cmd.ExecuteReader
Agetxt.Clear()
While myReader.Read()
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class
Check this code. This is for 3 checkboxes. You can extend it for 10 checkboxes.
Have a look here:
Dim hbStr As String
Dim bgStr As String
Dim tcStr As String
If hb.Checked Then
hbStr = hb.Text
Else
hbStr = ""
End If
If bg.Checked Then
bgStr = bg.Text
Else
bgStr = ""
End If
If tc.Checked Then
tcStr = tc.Text
Else
tcStr = ""
End If
Dim cmd As New OleDbCommand
Dim conn As New OleDbConnection("Connection String")
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into Table1(ID,Age,Name,TC,HB.BG) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','" & Nametxt.Text & "','" & tcStr & "','" & hbStr & "','" & bgStr & "')"
cmd.ExecuteNonQuery()
Hope this helps you.
Sorry it save only TC not Hb.
If Hbtxt.Checked Then
cmd = New OleDbCommand("insert into Table1(ID,Age,Hb) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','" & Hbtxt.Text & "')", con)
Else
cmd = New OleDbCommand("insert into Table1(ID,Age,Hb,) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','')", con)
End If
If TCtxt.Checked Then
cmd = New OleDbCommand("insert into Table1(ID,Age,TC) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','" & TCtxt.Text & "')", con)
Else
cmd = New OleDbCommand("insert into Table1(ID,Age,TC) values ('" & IDtxt.Text & "','" & Agetxt.Text & "','')", con)
End If