Code does not work but has no errors - vb.net

I'm working on an information system and here's my syntax for update, it shows no errors, but it does not update my table. Anyone can help on this matter?
By the way, I'm using VB.Net 2010 and MS Access 2007.
Try
Dim conn As New OleDbConnection(gConnectionString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
Dim comm As New OleDbCommand( "UPDATE PropertiesPayors SET [PayorName]=#PayorName,[LotNumber]=#LotNumber,[LotArea]=#LotArea,[DateOfAward]=#DateOfAward,[DateDueForFullPayment]=#DateDueForFullPayment,[PurchasePrice]=#PurchasePrice,[ReAppraisedValue]=#ReAppraisedValue,[AmountDue]=#AmountDue,[TotalAmountPaid]=#TotalAmountPaid,[AmountUnpaid]=#AmountUnpaid,[PropertyRemarks]=#PropertyRemarks WHERE [PropertyID]=#PropertyPayorID ", conn)
With comm
With .Parameters
.AddWithValue("#PropertyPropertyID", Val(propertyPayorSessionID.ToString))
.AddWithValue("#PayorName", txtPayorName.Text)
.AddWithValue("#LotNumber", txtLotNumber.Text)
.AddWithValue("#LotArea", Val(txtLotArea.Text))
.AddWithValue("#DateOfAward", txtDateOfAward.Text.ToString)
.AddWithValue("#DateDueForFullPayment", txtDateOfFullPayment.Text.ToString)
.AddWithValue("#PurchasePrice", Val(txtPurchasePrice.Text))
.AddWithValue("#ReAppraisedValue", Val(txtReAppraisedValue.Text))
.AddWithValue("#AmountDue", Val(txtAmountDue.Text))
.AddWithValue("#TotalAmountPaid", Val(txtTotalAmountPaid.Text))
.AddWithValue("#AmountUnpaid", Val(txtAmountUnpaid.Text))
.AddWithValue("#PropertyRemarks", txtRemarks.Text)
End With
.ExecuteNonQuery()
End With
msg = MsgBox("Record Updated.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Update Payor")
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Query Error")
End Try
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Connection Error")
End Try

You just have a typo on your code
Replace
#PropertyPropertyID
with
#PropertyPayorID
then arrange your parameter order same as your update statement.
And try this :
Try
Dim conn As New OleDbConnection(gConnectionString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
Dim comm As New OleDbCommand("UPDATE PropertiesPayors SET [PayorName]=#PayorName,[LotNumber]=#LotNumber,[LotArea]=#LotArea,[DateOfAward]=#DateOfAward,[DateDueForFullPayment]=#DateDueForFullPayment,[PurchasePrice]=#PurchasePrice,[ReAppraisedValue]=#ReAppraisedValue,[AmountDue]=#AmountDue,[TotalAmountPaid]=#TotalAmountPaid,[AmountUnpaid]=#AmountUnpaid,[PropertyRemarks]=#PropertyRemarks WHERE [PropertyID]=#PropertyPayorID ", conn)
With comm
With .Parameters
'.AddWithValue("#PropertyPayorID", Val(propertyPayorSessionID.ToString)) move this to the last part
.AddWithValue("#PayorName", txtPayorName.Text)
.AddWithValue("#LotNumber", txtLotNumber.Text)
.AddWithValue("#LotArea", Val(txtLotArea.Text))
.AddWithValue("#DateOfAward", txtDateOfAward.Text.ToString)
.AddWithValue("#DateDueForFullPayment", txtDateOfFullPayment.Text.ToString)
.AddWithValue("#PurchasePrice", Val(txtPurchasePrice.Text))
.AddWithValue("#ReAppraisedValue", Val(txtReAppraisedValue.Text))
.AddWithValue("#AmountDue", Val(txtAmountDue.Text))
.AddWithValue("#TotalAmountPaid", Val(txtTotalAmountPaid.Text))
.AddWithValue("#AmountUnpaid", Val(txtAmountUnpaid.Text))
.AddWithValue("#PropertyRemarks", txtRemarks.Text)
.AddWithValue("#PropertyPayorID", Val(propertyPayorSessionID.ToString))
End With
.ExecuteNonQuery()
End With
msg = MsgBox("Record Updated.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Update Payor")
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Query Error")
End Try
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Connection Error")
End Try
This will solve your problem.
see also: OleDbCommand parameters order and priority for reference.
Best Regards!

If I remember correctly, by default, there is no relation between the name of the place holders in the query and the name of the parameters. As BizApps has said, you should place your parameters in the same order as defined in your query; which means that PropertyPayorID should come last when you add it to your Parameters collection. The names for the Parameters collection are to be used only locally; like for changing some properties of the individual parameters.
Also, I don't remember if you can use named parameters in your query string as a place holder or if you must use a ? instead; something like Update PropertiesPayors SET [PayorName]=?, ...

The command statement .ExecuteNonQuery returns the number of rows which were affected.
This means if you used...
intRowsAffected = .ExecuteNonQuery()
And the value returned into the variable intRowsAffected was ZERO (0)
Then that means a record with the same value for your field PROPERTYID (meaning the value you passed into the parameters collection... PROPERTYPAYORSESSIONID) does not exist!
And thats why you are not recieving any errors and nor is your database being updated.
To double check this...
Where your code statement .EXECUTENONQUERY() is...
You can replace it with the following...
intRowsAffected = .ExecuteNonQuery()
Messagebox(intRowsAffected & " Data rows were updated.")
If the messagebox shows zero rows were updated (no rows were updated) then your next step would be to MANUALLY check the database and see if the row ACTUALLY exists and if it has the SAME key value that you are using to identify the row - which I assume is the property-payor-session-id.
Also keep in mind that the session-id is apt to change with each session and not static all the time.

Related

Is there a way to avoid getting an error when I use one of two textboxes to search from database?

I have two textboxes that I can use to search from database but it is not all the time when I use two textboxes to search.
Sometimes I use one but when i do so I get an error:
"Syntax error missing operator in query expression"
because the other textbox is empty. This only happens when I am using >=.
It seems to want all textboxes to have text.
Sub search()
Try
DataGridRecords.Rows.Clear()
conn.Open()
Dim cmd As New OleDb.OleDbCommand("Select * from tblDies where `IDSIZE` >= " & txtIdSize.Text & " OR `ODSIZE` >= " & txtOdSize.Text & " ", conn)
dr = cmd.ExecuteReader
While dr.Read
DataGridRecords.Rows.Add(dr.Item("ID"), dr.Item("DIENUMBER"), dr.Item("DESCRIPT"), dr.Item("OLDNUMBER"), dr.Item("CODE"), dr.Item("QUANTITY"), dr.Item("IDSIZE"), dr.Item("ODSIZE"), dr.Item("HEIGHT"), dr.Item("FLANGE HT"), dr.Item("FLANGE DIA"), dr.Item("CuRef"), dr.Item("CUTEL"), dr.Item("CuContact"), dr.Item("Price-selling"), dr.Item("P/no"), dr.Item("Stoksize"), dr.Item("Material"), dr.Item("Shore"), dr.Item("DieChkd"), dr.Item("DIECOST"), dr.Item("DATE"), dr.Item("REMARKS"), dr.Item("PRREF"))
End While
dr.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub

VB.NET database is not in MS Access and login error

I use Microsoft Access to store the data. The register form shows msgbox that the data was saved but there isn't any data stored in the table when I check the table on Microsoft Access. Is it supposed to be like that or did I code wrong?
This is my register code
If PasswordTextBox.Text.Length >= 8 Then
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb")
Dim insert As String = "Insert into Table1 values('" & NameTextBox.Text & "','" & Staff_IDTextBox.Text & "','" & Phone_NoTextBox.Text & "','" & UsernameTextBox.Text & "','" & PasswordTextBox.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
'cmd.ExecuteNonQuery()
MsgBox("Saved")
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
Catch ex As Exception
MsgBox("Error")
End Try
Else
MsgBox("Password must be more than 8 character")
End If
End If
This is my login code
uname = UsernameTextBox.Text
pword = PasswordTextBox.Text
Dim query As String = "Select password From Table1 where name= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login succeed")
Else
MsgBox("Login failed")
UsernameTextBox.Clear()
PasswordTextBox.Clear()
End If
There is an error at this line
pass = cmd.ExecuteScalar().ToString
It says:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Your "cmd.ExecuteNonQuery" is commented out, so the code will not save anything to the database.
You should close your connection after executing the INSERT command.
By default the table will have auto-numbered field as the first item in the table. You will need to remove this field from your table for that specific INSERT command to work.
Or you may need to use a slightly different INSERT command. It is useful to have auto-numbered ID fields in a table.
You probably should catch the exception and display ex.Message in your message box rather then "Error". The ex.Message will be much more helpful to you in debugging your program.
I have made all of these mistakes in my code at one time or other.
Your Login Code;
1)
You should catch the exception message and display in it a message box. This will make debugging faster.
The actual exception in your code will read "{"No value given for one or more required parameters."}
Your query is incorrect.
You should do the open, query, and close of the connection inside the Try-Catch block. Test for a null password afterwards to determine if the username does not exist.
Two separate answers provided, because you have two very separate questions.
Best wishes...

how can i push a msgbox if record is not found in Database using vb.net

seeking help how i can push a msgbox error if a record is not in the database or no data in the database. im using vb.net and sql to check the record. not sure how to do,
here is my code
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
'Main.BGCPnl.Visible = True
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
//>Here is my code for the error message when record is not
found, im not sure what will be the right code.
i used count parameter
BGCEmp = dr(ADS.UserEmpID)
If BGCEmp.Count = 0 Then
MsgBox("no record")
Exit Sub
End If
End While
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
You should learn how to properly use the Read method and the HasRows property of your data reader. If there can never be more than one record but there might be none then use just Read:
If myDataReader.Read() Then
'There is a row and you can access its data here.
Else
'There are no rows.
End If
If there may be multiple rows and either there can't be no rows or you don't need to do anything specific in the case that there are no rows then just use Read:
While myDataReader.Read()
'Access the current row here.
End While
If there are no rows then you never enter the loop and execution simply continues after that.
If there may be zero, one or more rows and you do need to do something specific in the case where there are none, use both HasRows and Read:
If myDataReader.HasRows Then
'There is at least one row so read the data.
While myDataReader.Read()
'Access the current row here.
End While
Else
'There are no rows.
End If
There may be situations where you only care whether there is data but you don't need the data itself. In that case, just use HasRows:
If myDataReader.HasRows Then
'There is a at least one row
Else
'There are no rows.
End If
In cases like that though, I'd suggest that you should be doing something like using a COUNT function in your query and calling ExecuteScalar rather than calling ExecuteReader.
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
End While
Else
MessageBox.Show("No Record found", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
Read documentation about Read() and HasRows.

Validate SQL data and check for Null

I have a textbox(txtOrderNum) where you enter an 'order' number and update a 'userfield' based on a date that is generated in another textbox(txtDate), I want to validate that the 'order' number entered matches the 'Order' number in the database, then update 'UserField1' only if its NULL, if it doesn't match then do nothing.
My goal, I don't want to overwrite data that is already in the Userfield1, and I want to ensure I update the correct 'Order' number that exist.
****I've updated my code based on suggestion below, I just need to validate if 'Order' number exist AND matches the order number entered in the textbox, then run update query. (also need to parameterized the query, I have some ideas but could use some help)****
Public Sub executequery(ByVal query As String)
Try
Dim cmd As New SqlCommand(query, conn)
conn.Open()
If (conn.State = ConnectionState.Open) Then
cmd.ExecuteNonQuery()
conn.Close()
Else
MessageBox.Show("Check Connection")
conn.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
Return
Finally
conn.Close()
End Try
End Sub
'My call Event via Enter Key within Textbox (txtOrdernum)
Dim conn As New SqlConnection("My data source")
Try
Dim updatequery As String = ("UPDATE [DATA].[dbo].[Order] SET [Userfield1] = '" & txtDate.Text.Trim() & "' WHERE [order] ='" & txtOrdernum.Text.Trim() & "' AND [Userfield1] IS NULL")
If e.KeyChar = Chr(13) Then 'Chr(13)
If txtOrdernum.Text.Length >= 8 Then
'MessageBox.Show(updatequery)
executequery(updatequery)
Else
MessageBox.Show("Invalid Order Number'")
End If
Catch ex As Exception
MsgBox(ex.ToString)
Return
End Try
As N0Alias stated, add "AND [UserField1] IS NULL".
Just be careful with the way you build your query. Building one like your example can allow SQL injection.
You should use the 'SqlCommand.Parameters' property to add values into your query.

Error: Syntax error in UPDATE statement

the error i get while executing the code below in OleDb
Try
con.Open()
Dim cmd As New OleDbCommand("Select * from customer", con)
cmd.CommandText = " update customer set hr =#hr,min =#min "
cmd.Parameters.AddWithValue("#hr", ComboBoxHr.SelectedIndex.ToString())
cmd.Parameters.AddWithValue("#min", ComboBoxMin.SelectedIndex.ToString())
cmd.ExecuteNonQuery()
TwoDigit(ComboBoxHr)
MessageBox.Show("CONRATULATIONS! ...Click the Start button to see the changes")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
Which works fine if i remove the "min" part.
What could be the reason?
I believe AakashM is right. You can however use a keyword as a column name as long as you put it in [] like
Try
con.Open()
Dim cmd As New OleDbCommand("Select * from customer", con)
cmd.CommandText = " update customer set hr =#hr,[min] =#min "
cmd.Parameters.AddWithValue("#hr", ComboBoxHr.SelectedIndex.ToString())
cmd.Parameters.AddWithValue("#min", ComboBoxMin.SelectedIndex.ToString())
cmd.ExecuteNonQuery()
TwoDigit(ComboBoxHr)
MessageBox.Show("CONRATULATIONS! ...Click the Start button to see the changes")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
MIN is a keyword in SQL (it's the aggregate function for finding the minimum of a group of values). Either use a different name for your column, or enclose it in [ square brackets ] - I'm not actually sure if this will work in Access, mind...