Visual Basic 2010 Express: Check if my.settings.username has a value - vb.net

VISUAL BASIC: You know how you can make your own settings in your program setting/properties, well I made a register system for a software. You register by entering a password and username then pressing 'Register' to save the username and password to My.Settings.Username and My.Settings.Password using My.Settings.Save().
The code: My.Settings.Username = TextBox1.Text
My.Settings.Password = TextBox2.Text
My.Settings.Save()
This all works perfectly but how can I prevent the user from changing it again.
This is my code so far:
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim res As MsgBoxResult
If Not My.Settings.Username = String.Empty And
My.Settings.Password = String.Empty Then
MsgBox("You have registered a WCUE account, please use 'CHANGE PASSWORD' in 'Settings' to do so.", MsgBoxStyle.Exclamation, "Not possible.")
ElseIf TextBox1.Text = String.Empty Or
TextBox2.Text = String.Empty Then
MsgBox("Don't press the register button if the text boxes are empty!", MsgBoxStyle.Critical, "Fill all required fields please.")
Else
If TextBox1.Text = My.Settings.Username And
TextBox2.Text = My.Settings.Password Then
MsgBox("If you are trying to log in then press the 'Log-in' text below the register button!", MsgBoxStyle.Exclamation, "You have already registered!")
Else
res = MsgBox("Register a WCUE account?", MsgBoxStyle.YesNo, "Create")
If res = MsgBoxResult.Yes Then
My.Settings.Username = TextBox1.Text
My.Settings.Password = TextBox2.Text
My.Settings.Save()
MsgBox("You can now login to WCUE and set the time limit on this user!", MsgBoxStyle.Information, "YEAH - Register successful!")
ElseIf res = MsgBoxResult.No Then
MsgBox("You should register as quick as possible before someone unauthorized sets a password!!", MsgBoxStyle.Exclamation, "Suit yourself.")
End If
End If
Exit Sub
End If
End Sub
The FIRST if statement is what I am having trouble with, I tried to check if My.Settings.Username and My.Setting.Password contains a value (string) which should be the username and password, if it does not then you can register but if it does contain a value then it tells you that someone has already registered. Nothing happens?
I hope this is clear enough, please help!

I ~think~ this is what you're trying to do...
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
If My.Settings.Username <> String.Empty AndAlso My.Settings.Password <> String.Empty Then
MsgBox("You have registered a WCUE account, please use 'CHANGE PASSWORD' in 'Settings' to do so.", MsgBoxStyle.Exclamation, "Not possible.")
Else
If TextBox1.Text = String.Empty OrElse TextBox2.Text = String.Empty Then
MsgBox("Don't press the register button if the text boxes are empty!", MsgBoxStyle.Critical, "Fill all required fields please.")
Else
Dim res As MsgBoxResult
res = MsgBox("Register a WCUE account?", MsgBoxStyle.YesNo, "Create")
If res = MsgBoxResult.Yes Then
My.Settings.Username = TextBox1.Text
My.Settings.Password = TextBox2.Text
My.Settings.Save()
MsgBox("You can now login to WCUE and set the time limit on this user!", MsgBoxStyle.Information, "YEAH - Register successful!")
ElseIf res = MsgBoxResult.No Then
MsgBox("You should register as quick as possible before someone unauthorized sets a password!!", MsgBoxStyle.Exclamation, "Suit yourself.")
End If
End If
End If
End Sub

Related

Securing records when it comes to editing

Assuming that there's value in all of the textfields and comboboxes. I want that when i click the edit button, there will be a pop up window that will require the users password before enabling the text fields.. is it possible? if yes? what's the code/syntax. Thanks in advance!
Yes, it possible, here i used Mike as a username and Mike124 as a password, here is the code to do that :
'Here is the click event when the user clicks on the edit button
Private Sub EditBUT_Click(sender As Object, e As EventArgs) Handles EditBUT.Click
RecheckUsername: Dim UserNameInput As String = InputBox("Please enter your username :")
If UserNameInput = "Mike" And UserNameInput <> "" Then
ReheckPassword: Dim PasswordInput As String = InputBox("Please enter your password :")
If PasswordInput = "Mike124" And PasswordInput <> "" Then
'Enable the all the fields here because the username and the password are correct
Else
'The password is wrong
MsgBox("Please check your password and try again")
GoTo ReheckPassword
End If
Else
'The username is wrong
MsgBox("Please check your username and try again")
GoTo RecheckUsername
End If
End Sub
If you want a way to store the username and the password, you can use My.Settings.Username and My.Settings.Password, but first you need to define them in the properties of your solution, just go to the Project tab in the Toolbar and click on Properties, then go to the Settings tab and set the Username and the Password variables.
Hope that helped you with what you need :)
Private Sub ACCOUNT_RECHECK()
Dim UserNameInput As String = InputBox("Please Enter your Username:")
Dim PasswordInput As String = InputBox("Please Enter your Password:")
Try
dbconnect.Open()
qInsert = "Select * from tblAdmin where Admin_UName='" & UserNameInput & "' and Admin_Password='" & PasswordInput & "'"
dbcommand = New OleDbCommand(qInsert, dbconnect)
dbcommand.ExecuteNonQuery()
Dim dr = dbcommand.ExecuteReader
If dr.Read = True Then
AccountType1 = dr("Admin_Type")
AccessGranted1 = True
dbconnect.Close()
Else
AccessGranted1 = False
End If
dbconnect.Close()
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
ACCOUNT_RECHECK()
If AccountType1 = False Then
MsgBox("INVALID! YOU'RE NOT ALLOWED TO MODIFY THIS DATA!", MsgBoxStyle.Exclamation)
End If
If AccessGranted1 = True Then
MsgBox("ACCESS GRANTED!", MsgBoxStyle.Information)
If AccountType1 = 1 Then
TAGA_ENABLE()
TAGA_ENABLEB()
ElseIf AccountType1 = 2 Then
MsgBox("Sorry, your access role is only for viewing! Kindly ask the Admin to change your role to modify this data", MsgBoxStyle.Information)
End If
End If
End Sub

How to limit user for login more than three times in this vb.net coding

How can I modify the following code to limit a user to three login attempts?
Public Class Form3
Dim Attemp As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "1" And TextBox2.Text = "1" Or
TextBox1.Text = "2" And TextBox2.Text = "2" Then
MsgBox("You are Now Logged In as User Rights", MsgBoxStyle.Information, "Login")
Form5.Show()
Close()
Else
If TextBox1.Text = "" And TextBox2.Text = "" Then
MsgBox("No Username and/or Password Found!", MsgBoxStyle.Critical, "Error")
Else
If TextBox1.Text = "" Then
MsgBox("No Username Found!", MsgBoxStyle.Critical, "Error")
Else
If TextBox2.Text = "" Then
MsgBox("No Password Found!", MsgBoxStyle.Critical, "Error")
Else
MsgBox("Invalid Username And/Or Password!", MsgBoxStyle.Critical, "Error")
End If
End If
End If
End If
End Sub
End Class
You have to add something like Attempt = Attempt + 1 just before the last end if. Then you can check Attempt variable in the first if with an and.

Please complete required fields message box

I'm trying to do a "Please complete required fields" messagebox.
Tt does show up but "Account Created" also pops out just right after "Please complete required fields" appears whenever I try entering even one character in a textbox or clicking one of the two radio button.
Also instead of "Please complete required fields", "User already exists!" shows up whenever the fields are empty.
Can somebody tell me what's wrong with my codes?
Thank you....
Public Class CreateAccount
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname, #pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
conn.Open()
Dim strUsername As String = TextBox1.Text
Dim boolUsernameExists As Boolean = False
Using dbConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb")
dbConnection.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", dbConnection)
dbCommand.Parameters.AddWithValue("#uname", strUsername)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result > 0 Then
boolUsernameExists = True
End If
End Using
dbConnection.Close()
End Using
If boolUsernameExists Then
MessageBox.Show("Username already exists!")
Return
End If
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
conn.Close()
If TextBox1.Text = "" Or TextBox2.Text = "" Or RadioButton1.Checked = False Or RadioButton2.Checked = False Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Hide()
LoginUser.Show()
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
Dim KeyAscii As Short = Asc(e.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.Back '<--- this is for backspace
Case 13
e.Handled = True
SendKeys.Send("{TAB}") '<---- use to tab to next textbox or control
KeyAscii = 0
Case Is <= 32
' KeyAscii = 0
Case 48 To 57 '<--- this is for numbers
Exit Sub
Case 65 To 90 '<--- this is for Uppercase Alpha
Exit Sub
Case 97 To 122 '<--- this is for Lowercase Alpha
Exit Sub
Case Else
e.Handled = True
MessageBox.Show("You can only input letters and numbers!", "Create Account")
End Select
End Sub
Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
End Class
I agree with DavidSdot, your code is out of order.
Here is an example that might work. I say might because im not very good at vb.net. So you might need to change a few things to make it work. However, that being said, the following might do you well regarding the correct order in which it should go.
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
If ((TextBox1.Text <> "" And TextBox2.Text <> "") And (RadioButton1.Checked <> False Or RadioButton2.Checked <> False)) Then
conn.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", conn)
dbCommand.Parameters.AddWithValue("#uname", TextBox1.Text)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result = 0 Then
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname,#pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
Else
MessageBox.Show("Username already exists!")
Return
End If
End Using
Else
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
conn.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
You should really take a look at the logic of Button1_click sub, because it is really hard to understand.
You opening your database twice
you already inserted a user with username="" and password="" thats why you get user exists message when you have not enter anything
Account created successfully! is always shown after Please complete the required fields as there is no check/return/whatever when fields as missing
No idea why the DB Insert is called on every keystroke as there is no code for that in what you posted

How to validate a username password and usertype login in Vb.net?

How to validate a username and password to login and then also check the usertype, based on which different events can be triggered?
for example admin has certain privileges and normal user has different privileges.
Public Class Login
Dim con As New OleDb.OleDbConnection
'new connection to database
Dim dbprovider As String
'to gets the probider name
Dim dbsource As String
'to gets the database provider name
Dim ds As New DataSet
'dataset to table
Dim da As OleDb.OleDbDataAdapter
'databaseAdapter to dataset and database
Dim sql As String
'sql command
Dim usrname1, pswd1, usrtype As String
Dim maxrows, incdec As Integer
'string variables
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'validation of username and password
If txtb_uname.Text = usrname1 And txtb_pwd.Text = pswd1 Then
If usrtype = "admin" Then
Score.Show()
Score.btn_delete.Enabled = False
Score.btn_update.Enabled = False
Score.Button2.Enabled = False
Score.Button1.Enabled = False
'username and password correct go to the netx page
ElseIf txtb_uname.Text = usrname1 And txtb_pwd.Text = "" Then
MsgBox("Enter Password")
'blank password control
ElseIf txtb_uname.Text = "" And txtb_pwd.Text = pswd1 Then
MsgBox("Enter Username")
'blank username control
ElseIf txtb_uname.Text = usrname1 And txtb_pwd.Text <> pswd1 Then
MsgBox("Invalid Password")
'incorrect pasword
ElseIf txtb_uname.Text <> usrname1 And txtb_pwd.Text = pswd1 Then
MsgBox("Invalid Username")
'incorrect username
ElseIf txtb_uname.Text = "" And txtb_pwd.Text = "" Then
MsgBox("enter Username")
'blank username and password
Else
MsgBox("invalid usertype")
End If
Else
MsgBox("Invalid Username & or Password")
'incorrect username and password
End If
End Sub
Lets assume that your database has a table containing the username, password and a boolean which is called something like isAdmin and can be set on true or false, depending on the users rights.
Now you have to use your DB connection to validate the username and the password. Here is a little example:
Public Shared Function Login(ByVal Name As String, ByVal Password As String) As Boolean
Shared OleDbConString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Settings.Netzwerkpfad & ";" 'you'll have to enter your own provider etc. I just copied it from another project
Shared con As OleDbConnection = New OleDbConnection(OleDbConString) 'establish the connection
Shared cmd As New OleDbCommand 'your sql statement
Shared reader As OleDbDataReader 'Saving the data you'll get
Dim Checkpassword String = "" 'The string where you'll put the password you get from the databse
Dim isAdmin as boolean = False
Try
cmd.Connection = con
cmd.CommandText = "SELECT Password, isAdmin FROM tbl_User WHERE Name = '" & Name & "';" 'tbl_User is just the table name, this may be different in your DB
con.Open() 'opens the database connection
reader = cmd.ExecuteReader 'executes your command
Do While reader.Read
Checkpassword = reader("Password") 'reader("Password") returns the column "Password" in your databse
isAdmin = reader("isAdmin") 'Returns true or false depending on the users rights
Loop
If Password.Equals(Checkpassword ) Then 'Checks if the entered password is correct
If isAdmin = True Then 'Check if Admin and based on the outcome call the functions or save the outcome into global variables
Else
End If
Else
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error while trying to log in", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return Nothing
Finally
con.Close()
End Try
End Function
Public Class frmAdminLoginpage
Dim ErrorCount As Integer
Private Sub frmAdminLoginpage_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ErrorCount = 0
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)
Me.Close()
End Sub
Private Sub lblCreateAccount_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblCreateAccount.LinkClicked
frmRegister.Show()
Me.Hide()
End Sub
Private Sub lblForgotPassword_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblForgotPassword.LinkClicked
frmForgotPassword.Show()
Me.Hide()
End Sub
Sub ClearControls()
txtLoginID.Text = ""
txtLoginPassword.Text = ""
txtLoginID.Focus()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Clear text
ClearControls()
End Sub
Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim strConnectionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim strSQL As String
' Check if ID or password is empty
If txtLoginPassword.Text = "" Or txtLoginID.Text = "" Then
MessageBox.Show("Please Enter your ID and Password.", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields was supply
' Check if user exist in database
' Connect to Database
strConnectionString = "Data Source=LENOVO-PC; Initial Catalog=VB; Integrated Security=True"
Try
'Database records will verify the Staff ID, password and position from the Staff Database
strSQL = "Select * FROM Staff WHERE StaffID='" & txtLoginID.Text & "'And Password = '" & txtLoginPassword.Text & "'And Position='Administrator'"
'strSQL = "Select * FROM Staff WHERE Position='Administrator'"
sqlCnn = New SqlConnection(strConnectionString)
'Open Database Connection
sqlCnn.Open()
sqlCmd = New SqlCommand(strSQL, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader
If sqlReader.Read() Then
frmSales_Admin.Show()
Me.Hide()
Else
' If user enter wrong ID and password
' Throw an error message
MessageBox.Show("Incorrect User ID and Password..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ErrorCount = ErrorCount + 1
'Clear all fields
txtLoginID.Text = ""
txtLoginPassword.Text = ""
'Focus on login ID field
txtLoginID.Focus()
'If login was not successful at the first time, the user will only have two more Login attempts left
If (ErrorCount = 1) Then
lblNotify.Text() = "You have 2 login attempts left"
'If login was not successful for the second time, the user will only have one more Login attempts left
ElseIf (ErrorCount = 2) Then
lblNotify.Text() = "You have 1 login attempt left"
'If login was not successful for the third time, the user will not have anymore attempts left
ElseIf (ErrorCount = 3) Then
MessageBox.Show(" You have exceeded the maximum login attempts. System is now exiting. ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
'The system will then exit after the message box is closed
Application.Exit()
End If
End If
Catch ex As Exception
MessageBox.Show("Failed to connect to Database.", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
Private Sub chkShowPassword_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowPassword.CheckedChanged
'To Make Password Visible
If chkShowPassword.Checked Then
txtLoginPassword.PasswordChar = ""
ElseIf chkShowPassword.Checked = False Then 'To make password not visible
txtLoginPassword.PasswordChar = "*"
End If
End Sub
Private Sub txtLoginID_DoubleClick(sender As Object, e As EventArgs) Handles txtLoginID.DoubleClick
txtLoginID.Clear()
txtLoginID.Focus()
End Sub
Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
'To go back to the main page of the app
frmSmartBookStore.Show()
Me.Hide()
End Sub
Private Sub txtLoginPassword_KeyDown(sender As Object, e As KeyEventArgs) Handles txtLoginPassword.KeyDown
Dim strConnectionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim strSQL As String
'If user press enter key on password textbox
If e.KeyCode = Keys.Enter Then
If txtLoginPassword.Text = "" Or txtLoginID.Text = "" Then
MessageBox.Show("Please Enter your ID and Password.", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields was supply
' Check if user exist in database
' Connect to Database
strConnectionString = "Data Source=LENOVO-PC; Initial Catalog=VB; Integrated Security=True"
Try
strSQL = "Select * FROM Staff WHERE StaffID='" & txtLoginID.Text & "'And Password = '" & txtLoginPassword.Text & "'And Position='Administrator'"
'strSQL = "Select * FROM Staff WHERE Position='Administrator'"
sqlCnn = New SqlConnection(strConnectionString)
'Open Database Connection
sqlCnn.Open()
sqlCmd = New SqlCommand(strSQL, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader
If sqlReader.Read() Then
frmSales_Admin.Show()
Me.Hide()
Else
' If user enter wrong username and password combination
' Throw an error message
MessageBox.Show("Incorrect User ID or Password..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ErrorCount = ErrorCount + 1
'Clear all fields
txtLoginID.Text = ""
txtLoginPassword.Text = ""
'Focus on login ID field
txtLoginID.Focus()
'If login was not successful at the first time, the user will only have two more Login attempts left
If (ErrorCount = 1) Then
lblNotify.Text() = "You have 2 login attempts left"
'If login was not successful for the second time, the user will only have one more Login attempts left
ElseIf (ErrorCount = 2) Then
lblNotify.Text() = "You have 1 login attempt left"
'If login was not successful for the third time, the user will not have anymore attempts left
ElseIf (ErrorCount = 3) Then
MessageBox.Show(" You have exceeded the maximum login attempts. System is now exiting. ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
'The system will then exit after the message box is closed
Application.Exit()
End If
End If
Catch ex As Exception
MessageBox.Show("Failed to connect to Database.", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End If
End Sub
'if you have problems ask me at 0114280#kdu-online.com'strong text
End Class

How to count login attempts Visual Basic

I want to add a count of login attempts to my login function. When a user types a wrong username and password 3 times, the program should close down and show a message. Here is my code for the Login button in my Form1.vb:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "13Mendv" And TextBox2.Text = "Admin123" Or
TextBox1.Text = "Admin" And TextBox2.Text = "Admin123" Or
TextBox1.Text = "13PateS" And TextBox2.Text = "Staff123" Or
TextBox1.Text = "13KhetP" And TextBox2.Text = "Member123" Or
TextBox1.Text = "13PateN" And TextBox2.Text = "Scorer123" Or
TextBox1.Text = "13ChatP" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13BonnN" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13EarlJ" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13RajaA" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "1" And TextBox2.Text = "1" Or
TextBox1.Text = "13SchaJ" And TextBox2.Text = "Captain123" Then
Timer1.Start() 'Timer on Form1.vb show
ProgressBar1.Show() 'Progress bar on Form1.vb show
Label8.Show() 'Label8 on Form1.vb show
Button4.Show() 'Button4 on Form1.vb show
Else
If TextBox1.Text = "" And TextBox2.Text = "" Then
MsgBox("No Username and/or Password Found!", MsgBoxStyle.Critical, "Error") 'If statement for checking if there is any input in either username or password entry field
Else
If TextBox1.Text = "" Then
MsgBox("No Username Found!", MsgBoxStyle.Critical, "Error") 'Message box no username found
Else
If TextBox2.Text = "" Then
MsgBox("No Password Found!", MsgBoxStyle.Critical, "Error") 'Message box no password found
Else
MsgBox("Invalid Username And/Or Password!", MsgBoxStyle.Critical, "Error") 'Message box invlaid username and or password
TextBox2.Clear()
End If
End If
End If
End If
End Sub
What can I do to add a count into this code to properly notify the user of their 3 failed login attempts?
Public Class Form1
Dim attempts As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim user As String
user = TextBox1.Text
If user = "Jhayboy" Then
MsgBox("Access Granted")
Form2.Show()
Me.Hide()
ElseIf attempts = 3 Then
MsgBox("Maximum count of retries(3),And you'reach the maximum attempts!Try again later", MsgBoxStyle.Critical, "Warning")
Close()
Else
MsgBox("Username and Password is incorrect! re-enter again you currently have reached attempt " & attempts & " of 3.")
attempts = attempts + 1
TextBox1.Text = ""
TextBox1.Focus()
End If
End Sub
End Class
As several people have suggested, you could create a variable (cntAttempts) that keeps track of how many times the user tries to login, and if the count reaches 3, the program closes. Like this:
Private cntAttempts = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ... Then
Timer1.Start() 'Timer on Form1.vb show
ProgressBar1.Show() 'Progress bar on Form1.vb show
Label8.Show() 'Label8 on Form1.vb show
Button4.Show() 'Button4 on Form1.vb show
Else
cntAttempts += 1
If cntAttempts = 3 Then
MessageBox.Show("login failed")
Me.close()
End If
If TextBox1.Text = "" And TextBox2.Text = "" Then
...
Else
...
End If
End If
End Sub
HTH
I added the cnt as integer and increment it until cnt<=3 .
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Dim cnt As Integer = 0
If cnt <= 3 Then
If TextBox1.Text = "13Mendv" And TextBox2.Text = "Admin123" Or
TextBox1.Text = "Admin" And TextBox2.Text = "Admin123" Or
TextBox1.Text = "13PateS" And TextBox2.Text = "Staff123" Or
TextBox1.Text = "13KhetP" And TextBox2.Text = "Member123" Or
TextBox1.Text = "13PateN" And TextBox2.Text = "Scorer123" Or
TextBox1.Text = "13ChatP" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13BonnN" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13EarlJ" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13RajaA" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "1" And TextBox2.Text = "1" Or
TextBox1.Text = "13SchaJ" And TextBox2.Text = "Captain123" Then
Timer1.Start() 'Timer on Form1.vb show
ProgressBar1.Show() 'Progress bar on Form1.vb show
Label8.Show() 'Label8 on Form1.vb show
Button4.Show() 'Button4 on Form1.vb show
Else
cnt = cnt + 1
If TextBox1.Text = "" And TextBox2.Text = "" Then
MsgBox("No Username and/or Password Found!", MsgBoxStyle.Critical, "Error") 'If statement for checking if there is any input in either username or password entry field
Else
If TextBox1.Text = "" Then
MsgBox("No Username Found!", MsgBoxStyle.Critical, "Error") 'Message box no username found
Else
If TextBox2.Text = "" Then
MsgBox("No Password Found!", MsgBoxStyle.Critical, "Error") 'Message box no password found
Else
MsgBox("Invalid Username And/Or Password!", MsgBoxStyle.Critical, "Error") 'Message box invlaid username and or password
TextBox2.Clear()
End If
End If
End If
End If
End If
End Sub`
Dim a =0
If txtname.Text = "yourUsername" And txtpass.Text = "yourPassword" Then
Msgbox("Acces Granted")
a=0
Elseif txtname.Text <> "yourUsername" Or txtpass.Text <> "yourPassword" Then
a = MsgBox("INVALID USERNAME AND PASSWORD") + a
End if
If
a = 3 Then
End
End if
This is probably the best way to solve this issue:
If TextBox1.Text = "Username" And TextBox2.Text = "Password" Or
TextBox1.Text = "Admin" And TextBox2.Text = "Admin123" Then
MsgBox("Welcome!")
Me.Hide()
Form1.Show()
Else
If TextBox1.Text = "" And TextBox2.Text = "" Then
MsgBox("No Username and/or Password Found!", MsgBoxStyle.Critical, "Error")
Else
If TextBox1.Text = "" Then
MsgBox("No Username Found!", MsgBoxStyle.Critical, "Error")
Else
If TextBox2.Text = "" Then
MsgBox("No Password Found!", MsgBoxStyle.Critical, "Error")
Else
MsgBox("Invalid Username And/Or Password!", MsgBoxStyle.Critical, "Error")
TextBox2.Clear()
End If
End If
End If
End If
End Sub
End Class