Data mismatch in criteria expression in delete oledb command - vb.net

I'm simply putting the Oledb command code for delete but the problem is when I delete one of the data from the DGV and there's a message of Data type miss match in criteria expression. Here's the one of my screen shots in this problem:
Below was the codes here:
Dim com = New OleDbCommand("DELETE FROM CustInfo WHERE Customer_ID = '" & Me.Txt_CusID.Text & "'", con)
Try
com.ExecuteNonQuery()
MsgBox("Delete : SUCCESS!")
Me.Close()
ShowTable()
Txt_CusID.Text = ""
Txt_Full.Text = ""
Txt_Add.Text = ""
Txt_Con.Text = ""
Txt_Email.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Could you tell me about this problem or lacking something as soon as possible to run this command?

Related

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.

checkbox always return False vb.net

I want to display the message "True" when i check checkbox in DatagridView but it always display "False" im looking for solution this is my code
Try
'opening the connection
con.Open()
If row.Cells(15).FormattedValue = False Then
'store your delete query to a variable(sql)
sql = "DELETE FROM terres WHERE id = '" _
& CStr(row.Cells(3).FormattedValue) & "'"
MsgBox(row.Cells(3).FormattedValue)
'Set your MySQL COMMANDS
With cmd
.Connection = con
.CommandText = sql
End With
'Execute the Data
result = cmd.ExecuteNonQuery
End If
Next
'the condition is, if the result is equals to zero
'then the message will appear and says "No Deleted Record."
'and if not the message will appear and says "The Record(s) has been deleted.."
If result = 0 Then
MsgBox("No Deleted Record.")
Else
MsgBox("The Record(s) has been deleted.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'Close the connection
con.Close()
When building your DataTable/DataGridView try something like this for the check box column:
dtdgv.Columns.Add("Process", GetType(Boolean))
'More columns etc.
'Seriously look at table adapters and
'make SURE they wont work for your application
'Fill dtdgv
DataGridView1.DataSource = dtdgv
DataGridView1.Refresh()
Then when determining whether it is checked or not something to this effect:
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("Process").Value = True Then
'Stuff
End If
Next
That what you're looking for?

How to sort datagridview columns programmatically

I am being asked to sort columns on a VB.Net created DataGridView. It's not my code but I'm trying to help. Here is part of the code:
Try
Dim sqlSelect As String = "SELECT * FROM Manpower WHERE LogOutTime IS NULL AND LogInDate = #" & dateToday & "# ORDER BY CustomerName"
Dim myDataAdapter = New OleDbDataAdapter(sqlSelect, myWorkforceConnection)
myCommandBuilder = New OleDbCommandBuilder(myDataAdapter)
myDataAdapter.Fill(myDataTable)
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
If myDataTable.Rows.Count = 0 Then
MessageBox.Show("No records found.")
Exit Sub
End If
dgvManpower.DataSource = myDataTabl
dgvManpower.Columns("ID").Visible = False
dgvManpower.Columns("EmployeeName").Width = 175
dgvManpower.Columns("EmployeeName").SortMode = DataGridViewColumnSortMode.Automatic
dgvManpower.Columns("EmployeeName").HeaderText = "Employee Name"
When I run the application I'm not able to sort on the EmployeeName column. The Microsoft documentation claims that a Glyph will be added to the column header but that doesn't appear either. How can I get the column to be "sort-able" ?
I can't see anything in your code that would stop sorting.
Check the datagridview settings in the IDE, and ensure that datagridview has Enabled=True, and ColumnHeadersVisible=True.
Then click a column header and see what happens.