Delete button code sometimes working - vb.net

How to debug the following code?
Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
If vbYes Then
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "Delete From TB_stinfo where id=?"
cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("one record is deleted")
Catch ex As Exception
MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
Finally
dt.Clear()
Form1_Load(sender, e)
clear()
checkcon()
End Try
Else
MsgBox("This record is not deleted")
End If

I reformatted your code so it was more readable:
Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
If vbYes Then
Try
con.Open()
cmd.Connection = con cmd.CommandText = "Delete From TB_stinfo where id=?"
cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("one record is deleted")
Catch ex As Exception
MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
Finally
dt.Clear()
Form1_Load(sender, e)
clear()
checkcon()
End Try
Else
MsgBox("This record is not deleted")
End If
The number one issue I see here is that we do not see what the value of the key is you're deleting on , nor the format of the data that's in the table to delete from. It's impossible to determine what exactly is wrong from this code.
My suggestion is to set a breakpoint on this line cmd.ExecuteNonQuery() and see what the value of TextBox1.Text is and make sure it is what you expect it to be, look for leading/trailing spaces or anything else that's unexpected.. Other than that there isn't much else to go on here in terms of context.

Related

auto number in data grid view and access database

I wanted to make a program using access database and make it auto number the rows but when I delete a row the order of the rows is incorrect and the program starts with the last row number
The deletion code I used:
Sub delete()
Try
If MsgBox("Are You Sure Delete This Record", vbQuestion + vbYesNo) = vbYes Then
conn.Open()
Dim cmd As New OleDb.OleDbCommand("Delete from MedicineDB Where ID=#ID", conn)
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#ID", txtID.Text)
i = cmd.ExecuteNonQuery
If i > 0 Then
MsgBox("Record Delete Success !", vbInformation)
Else
MsgBox("Failed", vbCritical)
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
loadingDatagridView()
clear()
End Sub
that is the result:

How to fix "Invalid attempt to read when reader is closed vb.net"

invalid attempt to read when reader is closed error. vb.net
I have the code below that I use to login into MySQL but it keeps displaying the error 'invalid attempt to read when reader is closed' and then it logs in. I don't understand what could still be wrong with the code. Kindly assist, it's so frustrating. Thanks.
Try
ConnDB()
command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
Reader = command.ExecuteReader()
If Reader.Read = True Then
ComboBox1.Text = Reader.GetValue(2)
lblUser.Text = Reader.GetValue(3)
End If
If (Reader IsNot Nothing) Then
Reader.Close()
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
If ComboBox1.Text.Length > 0 Then
MainMenu.lblUserName.Text = Me.txtUsername.Text
MainMenu.lblType.Text = Me.ComboBox1.Text
MainMenu.lblOccupation.Text = Me.ComboBox1.Text
MainMenu.lblUser.Text = Me.lblUser.Text
Dim st As String = "Successfully logged in"
LogFunc(txtUsername.Text, st)
Me.Hide()
MainMenu.Show()
Else
MsgBox("Incorrect username or password..Login is Failed...Try again !", MsgBoxStyle.Critical, "Login")
txtUsername.SelectAll()
txtPassword.SelectAll()
txtUsername.Focus()
txtPassword.Text = ""
End If
command.Dispose()
' Reader.Close()
'command.Dispose()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
DisconnMy()
End Try
I expect it to log in successfully without displaying the error.
Sorry, I forgot to add this for my connection string.
Public Sub ConnDB()
con.Close()
Try
con.ConnectionString = "Server = '" & ServerMySQL & "'; " _
& "Port = '" & PortMySQL & "'; " _
& "Database = '" & DBNameMySQL & "'; " _
& "user id = '" & UserNameMySQL & "'; " _
& "password = '" & PwdMySQL & "'"
con.Open()
Catch ex As Exception
MsgBox("The system failed to establish a connection", MsgBoxStyle.Information, "Database Settings")
End Try
End Sub
In general it's not a good idea to use a "global", single connection for everything. Note that connection-pooling is enabled by default which means that .NET will take care of the physical connections. So you should create,open,use and close/dispose the connection where you use it.
I'm pretty sure that this will fix the issue:
Try
Using con As New MySql.Data.MySqlClient.MySqlConnection(MySettings.Default.SqlConnection)
Using command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
con.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
ComboBox1.Text = reader.GetValue(2)
lblUser.Text = reader.GetValue(3)
End If
' NOTE: you dont need to close the reader/command/connection
' if you use the Using-statement, it will use Dispose even in case of an error
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

How to prevent certain data from being inserted into the database with If Else statements?

I have two comboboxes, a messagebox and a Send button. When the app startups and I click on the Send button with the comboboxes and messagebox empty, a pop-up box comes up and says "Select a client" After doing this, I go back to the database and see that it has added a new record to that table, even though I didn't put in any data after clicking on the "Send" button. Same applies for when one of the three controls I have has data in it, but the other two don't, and the program asks me to enter that data before it succeeds. But it still adds the record despite having those If Statements. What am I doing wrong?
My code:
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values('" & cboClient.Text & "', '" & cboUser.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
If cboClient.Text = "" Then
MsgBox("Select a client")
ElseIf cboUser.Text = "" Then
MsgBox("Select a user")
ElseIf rtfMessage.Text = "" Then
MsgBox("Enter a message")
Else
MsgBox("Message Sent")
End If
con.Close()
End Using
I think you want something like this (note this does not address parameterization concerns):
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
If cboClient.Text = "" Then
MsgBox("Select a client")
ElseIf cboUser.Text = "" Then
MsgBox("Select a user")
ElseIf rtfMessage.Text = "" Then
MsgBox("Enter a message")
Else
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values('" & cboClient.Text & "', '" & cboUser.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
MsgBox("Message Sent")
End If
con.Close()
End Using
Similar solution to #OldProgrammer, with an attempt at parameterized insert.
Private Sub SendButton_Click(sender As System.Object, e As System.EventArgs) Handles SendButton.Click
Try
If writeMessage() Then
MessageBox.Show("Message sent.", "Success")
End If
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred sending this message:", ex.Message))
End Try
End Sub
Private Function writeMessage() As Boolean
If isValidMessage() Then
writeMessageInfo()
Return True
End If
Return False
End Function
Private Sub writeMessageInfo()
Using con As New SqlConnection(yourConnectionString)
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.Parameters.Add(New SqlParameter("clientValue", cboClient.Text))
cmd.Parameters.Add(New SqlParameter("userValue", cboUser.Text))
cmd.Parameters.Add(New SqlParameter("messageText", rtfMessage.Text))
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values(#clientValuem, #userValue, #messageText)"
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
End Sub
Private Function isValidMessage() As Boolean
If cboClient.SelectedIndex = -1 Then
MessageBox.Show("Please select a client.", "Missing info")
cboClient.Focus()
Return False
End If
If cboUser.SelectedIndex = -1 Then
MessageBox.Show("Please select a user.", "Missing info")
cboUser.Focus()
Return False
End If
If rtfMessage.Text = String.Empty Then
MessageBox.Show("Please enter a message.", "Missing info")
rtfMessage.Focus()
Return False
End If
Return True
End Function

Error showing while updating database with Identity Column

Please help me... i am trying to update my database from VB.net. It shows error. My code is given below....
Try
getConnect()
Dim strSQL As String
strSQL = " UPDATE DEPARTMENT SET [DEP_ID]=#DEP_ID,[DEPART]=#DEPART, [DEP_DSCRPTN]=#DEP_DSCRPTN WHERE [DEP_ID] = #DEP_ID"
Dim cmd As New SqlCommand(strSQL, Conn)
cmd.Parameters.AddWithValue("#DEP_ID", CInt(Me.DEPID.Text))
cmd.Parameters.AddWithValue("#DEPART", SqlDbType.VarChar).Value = CMBDEPT.Text
cmd.Parameters.AddWithValue("#DEP_DSCRPTN", SqlDbType.VarChar).Value = TXTDESC.Text
Conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Update Complete!", MsgBoxStyle.Information, "Update")
Catch ex As Exception
MsgBox("ERROR: " + ex.Message, MsgBoxStyle.Information, "Update")
Finally
Conn.Close()
BTNCLEAR.PerformClick()
End Try
And the error is:
ERROR: Cannot update identity column 'DEP_ID'
Remove [DEP_ID]=#DEP_ID, from the SET. It makes no sense to try and set it to the value already ensured by the WHERE anyway so it is clearly redundant and it is not permitted to update IDENTITY columns.
UPDATE DEPARTMENT
SET [DEPART] = #DEPART,
[DEP_DSCRPTN] = #DEP_DSCRPTN
WHERE [DEP_ID] = #DEP_ID
The error message is clear, remove the Set DEP_ID = #DEP_ID part.
Try
getConnect()
Dim strSQL As String
strSQL = "UPDATE DEPARTMENT SET [DEPART]=#DEPART," +
"[DEP_DSCRPTN]=#DEP_DSCRPTN WHERE [DEP_ID] = #DEP_ID"
Dim cmd As New SqlCommand(strSQL, Conn)
cmd.Parameters.AddWithValue("#DEP_ID", CInt(Me.DEPID.Text))
cmd.Parameters.AddWithValue("#DEPART", SqlDbType.VarChar).Value = CMBDEPT.Text
cmd.Parameters.AddWithValue("#DEP_DSCRPTN", SqlDbType.VarChar).Value = TXTDESC.Text
Conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Update Complete!", MsgBoxStyle.Information, "Update")
Catch ex As Exception
MsgBox("ERROR: " + ex.Message, MsgBoxStyle.Information, "Update")
Finally
Conn.Close()
BTNCLEAR.PerformClick()
End Try
If you find yourself in need to change an Identity column then I think you need to analyze better your database schema.

Code does not work but has no errors

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.