Message box won't display [duplicate] - vb.net

This question already has an answer here:
Not able to show error message if the email/password wrongly entered
(1 answer)
Closed 5 years ago.
I want a message box to appear if the email/ password is incorrect when logging in. However nothing happens with this else statement. Does it need to be placed somewhere else for it to work?
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
str1 = ("SELECT * FROM [UserData] WHERE [Username] = '" & TxtUserName.Text & "' AND [Password] = '" & TxtPassword.Text & "'")
Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
dr = cmd1.ExecuteReader
While dr.Read()
userFound = True
TxtPassword.Text = dr("Username").ToString
TxtUserName.Text = dr("Password").ToString
FirstNameToPass = dr("First Name").ToString
LastNameToPass = dr("Last Name").ToString
AddressToPass = dr("Address").ToString
EmailToPass = dr("Email").ToString
If userFound = True Then
UserAccountView.Show()
Me.Hide()
TxtPassword.Clear()
TxtUserName.Clear()
Else
MsgBox("Login is incorrect")
End If
End While
MyConn.Close()
End If

I would simply use a Count() to check if user exists and correct.
Note:
In NoAlias's answer it doesn't solve the problem that userFound will always be true.
So I implemented this solution there might be few errors since i'm not familiar with OleDb but nothing to big hopefully
I also implemented the Using as it is good practice to implement it when working with: IDisposable()
Using MyConn As New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
Dim check As String = "SELECT COUNT(*) FROM [UserData] WHERE [Username] = '" & TxtUserName.Text & "' AND [Password] = '" & TxtPassword.Text & "'"
Dim UserExist As Boolean = False
Dim command As OleDbCommand = New OleDbCommand(check, MyConn)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
If reader(0) = 0 Then
UserExist = False
Else
UserExist = True
End If
End While
End Using
If UserExist = True Then
Dim getData As String = "SELECT * FROM [UserData] WHERE [Username] = '" & TxtUserName.Text & "'"
Dim command2 As OleDbCommand = New OleDbCommand(getData, MyConn)
Using reader As OleDbDataReader = command2.ExecuteReader()
While reader.Read()
userFound = True
TxtPassword.Text = dr("Username").ToString
TxtUserName.Text = dr("Password").ToString
FirstNameToPass = dr("First Name").ToString
LastNameToPass = dr("Last Name").ToString
AddressToPass = dr("Address").ToString
EmailToPass = dr("Email").ToString
End While
End Using
Else
MsgBox("Login is incorrect")
End If
MyConn.Close()
End Using

If your SQL returns no results, which will be the case when the credentials are wrong, the MessageBox code will never be called. Put this code block after your While statement.
If userFound = True Then
UserAccountView.Show()
Me.Hide()
TxtPassword.Clear()
TxtUserName.Clear()
Else
MsgBox("Login is incorrect")
End If

Related

How solve this problem syntax error in UPDATE statement

This problem at syntax error for update statement then I don't know how to solve this problem
Private Sub editStaff()
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
If IDTextBox.Text <> "" And FirstTextBox.Text <> "" And SecondTextBox.Text <> "" And UsernameTextBox.Text <> "" And PasswordTextBox.Text <> "" Then
strSQL = "update Staff set First_Name = '" & FirstTextBox.Text & "', " &
"Second_Name = '" & SecondTextBox.Text & "', " & "Username = '" & UsernameTextBox.Text & "', " &
"Password = '" & PasswordTextBox.Text & "'" & " where ID = " & CInt(IDTextBox.Text) & ""
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MessageBox.Show("Update Successful")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
For some reason your validation If did not include the ID text box. I added validation for this text box. The OrElse is a short circuit. As soon as it finds a True it stops checking the conditions and proceeds to the next line.
This code
If con.State = ConnectionState.Closed Then
con.Open()
End If
is completely unnecessary if you keep your database objects local. Keeping them local allows you to ensure they are closed and disposed with Using...End Using blocks.
Don't open the connection until you need it which is directly before the .Execute... line. Use parameters to avoid Sql Injection. Also your Update statement is much easier to write without all the single quotes and double quotes and ampersands.
Caution In Access the order that the parameters appear in the Sql statement must match the order that they are added to the .Parameters collection.
Finally, you should NEVER store passwords as plain text. I will leave it to you to research salting and hashing and correct the code.
Private Sub editStaff()
Dim i As Integer
If Integer.TryParse(IDTextBox.Text, i) Then
MessageBox.Show("ID text box must be a number")
Return
End If
If IDTextBox.Text = "" OrElse FirstTextBox.Text = "" OrElse SecondTextBox.Text = "" OrElse UsernameTextBox.Text = "" OrElse PasswordTextBox.Text = "" Then
MessageBox.Show("Please fill in all text boxes")
Return
End If
Try
Using con As New OleDbConnection("Your connection string")
Dim strSQL = "Update Staff set First_Name = #FirstName, Second_Name = #SecondName, [Username] = #UserName, [Password] = #Password Where [ID] = #ID"
Using cmd As New OleDbCommand(strSQL, con)
With cmd.Parameters
.Add("#FirstName", OleDbType.VarChar).Value = FirstTextBox.Text
.Add("#SecondName", OleDbType.VarChar).Value = SecondTextBox.Text
.Add("#UserName", OleDbType.VarChar).Value = UsernameBox.Text
.Add("#Password", OleDbType.VarChar).Value = PasswordTextBox.Text
.Add("#ID", OleDbType.Integer).Value = CInt(IDTextBox.Text)
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Update Successful")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll" visual studio vb.net using database microsoft access

im a beginner in vb.net and when i start my coding the error "An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll" i dont know what to do. this is my code.
Dim cmd As New OleDbCommand("SELECT * FROM [login] WHERE [ID] & [Password] =" & TextBoxUsername.Text & TextBoxPassword.Text & "", myConnection)
myConnection.Open() '*its keep pointing at this*
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim userFound As Boolean
Dim userID As String = ""
Dim UserPassword As String = ""
While dr.Read
userFound = True
userID = dr("ID").ToString
UserPassword = dr("Password").ToString
Form2.Show()
Me.Hide()
End While
If userFound = False Then
MessageBox.Show("Invalid Username/Password")
'Button","User Validation", MessageBoxButton.OK , MessageBoxIcon.Error)'
End If
myConnection.Close()
End Sub
End Class**
You aren't currently wrapping your parameters in single quotes and your WHERE clause syntax appears to be off. It's likely you want something like this :
"SELECT * FROM [login] WHERE [ID] = '" & TextBoxUsername.Text & "' AND [Password] = '" & TextBoxPassword.Text & "'"
A larger issue here is that you should be using parameters to build your query, which can not only help you avoid issues like this, but it can also help prevent nasty things like SQL Injection :
' Build your connection '
Using(Dim myConnection As New OleDbConnection("{your-connection-string"}))
' Use parameters in your query '
Dim query = "SELECT * FROM [login] WHERE [ID] = ? AND Password = ?"
' Build your command to execute '
Using(Dim myCommand As New OleDbCommand(query, myConnection))
' Open your connection '
myConnection.Open()
' Add your parameters (these will replace the ? in your query)
myCommand.Parameters.AddWithValue("#ID",TextBoxUsername.Text)
myCommand.Parameters.AddWithValue("#Password",TextBoxPassword.Text)
Using(Dim myReader = myCommand.ExecuteReader())
If myReader.HasRows Then
' Do stuff '
userFound = True
userID = dr("ID").ToString
UserPassword = dr("Password").ToString
Form2.Show()
Me.Hide()
Else
' Do other stuff '
MessageBox.Show("Invalid Username/Password")
End If
End Using
End Using
End Using

How can I make this Login case sensitive?

Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
conn = New OleDbConnection("Provider = Microsoft.ace.Oledb.12.0; Data Source = C:\Users\matthew\Desktop\GSCS\Enrollment.accdb")
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Login WHERE UserName = '" & txtUserName.Text & "' AND [Password] = '" & txtPassword.Text & "'", conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim userFound As Boolean = False
While dr.Read()
userFound = True
UserName = dr("Username").ToString
Password = dr("Password").ToString
LevelOfAccess = dr("LevelOfAccess").ToString
End While
If txtUserName.Text = "" Or txtPassword.Text = "" Then
MessageBox.Show("Some fields missing")
ElseIf txtPassword.Text.Length < 6 Then
MessageBox.Show("Password should consists of 6-12 characters", "Error", MessageBoxButtons.OK)
ElseIf userFound = True Then
Dim st As String = "INSERT INTO AuditTrail (Username, DateOfUsage, Activity) VALUES ('" & txtUserName.Text & "', '" & Date.Now & "', '" & li & "')"
Dim cmd1 As New OleDbCommand(st, conn)
cmd1.ExecuteNonQuery()
If LevelOfAccess = 1 Then
DisplayForm(Dashboard, Main.pnlMain)
MessageBox.Show("Administrator")
ElseIf LevelOfAccess = 2 Then
DisplayForm(Dashboard1, Main.pnlMain)
MessageBox.Show("Employee")
End If
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "Invalid Login")
End If
conn.Close()
End Sub
This is my login code, can anybody help me how can I make it case sensitive? There are no error, but it is not casesensitive. Anyone who has the idea how I can make this case sensitive?
String.Compare(str1, str2, True))
try to use string.compare method instead of just "=" Sign
like this:
dim x as integer
x=String.Compare(str1, str2, False)
if x=0 then
'Put Codes Here If Password Is Correct
else
'put Code Here IF password Is Incorrect
end if

autofilling textboxes with database data based on a primary key entry into another textbox

i have the code below, it works fine but whenever i insert a student number that does not exist in the table, the rest of the textboxes will keep displaying data from the previous existing entry. This happens even when the i delete everything in the student number textbox.
how can i change it such that the rest of the textboxes are cleared in case the student number textbox is blank or contains a student number that does not exist in the database?
Thanks in advance.
' Try
Dim mycommand As SqlCommand = New SqlCommand()
Dim datareader As SqlDataReader = Nothing
myconnection.Open()
Dim query As String
query = " select StudentNo,Fullname,Year,Term,Class from StudentRegistration where StudentNo = '" & TxtStudentNo.Text & "' and (class = 'Senior 5A' or Class ='Senior 5S' or Class='Senior 6A' or class='Senior1 6S')"
mycommand = New SqlCommand(query, myconnection)
datareader = mycommand.ExecuteReader()
While datareader.Read
If datareader IsNot Nothing Then
' TxtStudentNo.Text = datareader.Item("StudentNo")
TxtName.Text = datareader.Item("FullName")
TxtYear.Text = datareader.Item("Year")
TxtTerm.Text = datareader.Item("Term")
TxtClass.Text = datareader.Item("Class")
End If
End While
myconnection.Close()
' Catch ex As Exception
'MessageBox.Show(ex.Message)
' End Try`
Add an else condition to reader and clear text boxes in that module.
While datareader.Read
If datareader IsNot Nothing Then
' TxtStudentNo.Text = datareader.Item("StudentNo")
TxtName.Text = datareader.Item("FullName")
TxtYear.Text = datareader.Item("Year")
TxtTerm.Text = datareader.Item("Term")
TxtClass.Text = datareader.Item("Class")
else
TxtName.Text = ""
TxtYear.Text = ""
TxtTerm.Text = ""
TxtClass.Text = ""
End If
hope theres no big deal more than this.
I finally changed my code to the one below and it's doing exactly what i want.
Private Sub getData()
Dim dt As New DataTable()
myconnection.Open()
Dim Mycommand As New SqlCommand("select Fullname,Year,Term,Class from StudentRegistration where StudentNo = '" & TxtStudentNo.Text & "'", myconnection)
Dim sqlDa As New SqlDataAdapter(Mycommand)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TxtName.Text = dt.Rows(0)("FullName").ToString()
TxtYear.Text = dt.Rows(0)("Year").ToString()
Else
TxtName.Text = ""
TxtYear.Text = ""
End If
myconnection.Close()
End Sub

VB.NET login form - using Oracle

In a Login form for VB.Net connected to an Oracle database.. Is there a way of inserting an If statement to direct different users to different forms.. Eg, an accountant to the accounting home page or a driver to a driver homepage even though all there ID's and passwords are in the one table within the database.
There is a POSITION field within the database and this is what I would like to use to differentiate the different users levels of access.
Here is the code working so far:
Dim conn As New OleDb.OleDbConnection
conn.ConnectionString = _
"Provider=msdaora;Data Source=orabis;User Id=112221800;Password=112221800;"
conn.Open()
Dim parmuser As New OleDb.OleDbParameter
parmuser.OleDbType = OleDb.OleDbType.Char
parmuser.Value = txtStaffNo.Text
Dim parmpass As New OleDb.OleDbParameter
parmpass.OleDbType = OleDb.OleDbType.Char
parmpass.Value = txtPassword.Text
Dim cmd As New OleDbCommand
cmd.Connection = conn
cmd = New OleDbCommand("select STAFFID,PASSWORD from STAFF where STAFFID ='" & txtStaffNo.Text & "' and PASSWORD ='" & txtPassword.Text & "'", conn)
cmd.CommandType = CommandType.Text
Dim dr As OleDb.OleDbDataReader
dr = cmd.ExecuteReader()
If txtStaffNo.Text = "" Or txtPassword.Text = "" Then
MessageBox.Show("You have not entered any values!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
ElseIf dr.Read() Then
txtStaffNo.Text = dr("STAFFID")
txtPassword.Text = dr("PASSWORD")
MsgBox("Access Allowed")
CustOption.Show()
Me.Hide()
Else
'MessageBox.Show("Wrong Username and Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
'intCount = intCount + 1
End If
In your SELECT statement, add position there so it would be:
cmd = New OleDbCommand("select POSITION, STAFFID,PASSWORD from STAFF where STAFFID ='" & txtStaffNo.Text & "' and PASSWORD ='" & txtPassword.Text & "'", conn)
Then after you validate the user, you just use a select case like:
Dim empPosition as string = dr("POSITION") ' assuming it's a string here
select case empPosition.toLower
case "driver"
' open driver form
case "accountant"
'open accountant form
' more case statements for other positions.
End Select