How to create a txt file that records login details? VB.NET - vb.net

I wanna create a txt file that stores the Username, Password, Date & Time, and User Type when "Log In" button is pressed. But all I know is how to create a txt file. Can anyone help me? Here's my code for my Log In button:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim username As String = ""
Dim password As String = ""
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:\Library Management System\LMS_Database.accdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT ID_Number FROM Users WHERE ID_Number = '" & txtUsername.Text & "' AND ID_Number = '" & txtPassword.Text & "'", cn)
cn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader()
If (dr.Read() = True And cboUserType.Text = "Student") Then
MsgBox("Welcome!", MsgBoxStyle.OkOnly, "Successfully logged in.")
frmViewBooks.Show()
txtUsername.Clear()
txtPassword.Clear()
cboUserType.SelectedIndex = -1
Me.Hide()
Else
If (txtUsername.Text = "admin" And txtPassword.Text = "ckclibraryadmin" And cboUserType.Text = "Administrator") Then
MsgBox("Welcome, admin!", MsgBoxStyle.OkOnly, "Successfully logged in.")
frmAdminWindow.Show()
txtUsername.Clear()
txtPassword.Clear()
cboUserType.SelectedIndex = -1
Me.Hide()
Else
MsgBox("Your username or password is invalid. Please try again.", MsgBoxStyle.OkOnly, "Login failed.")
txtUsername.Clear()
txtPassword.Clear()
cboUserType.SelectedIndex = -1
End If
End If
End Sub
I'd be getting the Date and Time value from my timer.
Private Sub frmLogIn_Load(sender As Object, e As EventArgs) Handles MyBase.Load
tmrLogIn.Start()
End Sub
Private Sub tmrLogIn_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrLogIn.Tick
lblTime.Text = DateTime.Now.ToString()
End Sub
Thank you!

There are a few things that I'd like to point out to maybe help you later on down the road. Data object generally implement iDisposable, it is a good idea to either wrap them in Using statements or dispose of them manually. Also, it is generally a good idea to wrap any database code into a Try/Catch exception handler because something can go wrong at any point you're trying to access outside data. Also, it is always a good idea to parameterize your query. Finally, you are only wanting to validate that a row is returned from your SQL statement, so your SQL statement should instead return the number of rows returned and then you can use the ExecuteScalar to get that one value returned.
With all of that out of the way, all you would need to do is append a line to a text file using the IO.File.AppendAllLines method using the data you already have if the login was validated.
Here is an example of implementing everything I suggested:
'Declare the object to return
Dim count As Integer = -1
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:\Library Management System\LMS_Database.accdb")
'Create a new instance of the command object
'TODO: If [Username] and [Password] are not valid columns, then change them
Using cmd As OleDbCommand = New OleDbCommand("SELECT Count([ID_Number]) FROM [Users] WHERE [Username] = #username AND [Password] = #password", con)
'Parameterize the query
With cmd.Parameters
.AddWithValue("#username", txtUsername.Text)
.AddWithValue("#password", txtPassword.Text)
End With
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
count = Convert.ToInt32(cmd.ExecuteScalar())
'Close the connection
con.Close()
End Using
If count > 0 Then
'Append the data to the text file
'TODO: Change myfilehere.txt to the desired file name and location
IO.File.AppendAllLines("myfilehere.txt", String.Join(",", {txtUsername.Text, txtPassword.Text, DateTime.Now, cboUserType.Text}))
'Check if it is a student or admin
If cboUserType.Text = "Student" Then
'Inform the user of the successfull login
MessageBox.Show("Welcome!", "Login Successfull", MessageBoxButtons.OK)
frmViewBooks.Show()
ElseIf cboUserType.Text = "Administrator" Then
'Inform the admin of the successfull login
MessageBox.Show("Welcome, admin!", "Login Successfull", MessageBoxButtons.OK)
frmAdminWindow.Show()
End If
'Reset and hide the form
txtUsername.Clear()
txtPassword.Clear()
cboUserType.SelectedIndex = -1
Me.Hi
Else
'Inform the user of the invalid login
MessageBox.Show("Invalid username and/or password. Please try again.", "Invalid Login", MessageBoxButtons.OK)
End If
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try

Your goal can be achieved in many ways.For example,you can create an access/sql/mysql database to store the required information.But if u want to use a textfile instead,you can store Username,password and other details on seperate lines.Then you can read each line from the text file and use it the way you want.So,which one u prefer? a database or text file? leave a comment and i'lll add the codes/instructions depending on your choice

Related

How to link to a relational database - visual basic

I am creating a flashcard application where each user can create flashcards which will be specific to them. I was wondering how I can link each flashcard they create to their specific account.
Imports System.Data.OleDb
Public Class CreateFlashcards
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New OleDbConnection
Private Sub btnCreateFlashcard_Click(sender As Object, e As EventArgs) Handles btnCreateFlashcard.Click
pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into Flashcards ([Front],[Back]) values ('" & txtFront.Text & "','" & txtBack.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(txtFront.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(txtBack.Text, String)))
MsgBox("You have successfully added the flashcard into your deck!")
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtFront.Clear()
txtBack.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
This works in that it adds the data into the access database but it does not link to the users account. I have also linked the tables in access
The login table
The flashcard table
As you can see the loginID key does not link
Normally, the connection string for Access contains the the path to the database file for the Data Source attribute.
You will need to add a field to your Flashcard table to hold the UserID. This will tie the 2 tables together.
Database objects like connections and commands need to be disposed as well as closed. Using...End Using blocks handle this for you even if have an error. In this code you both the connection and the command are included in the same Using block.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the sql command text and the connection to the constructor of the command.
When you are using parameters, which you should in Access and Sql Service, put the name of the parameter in the sql command text. It is not necessary to convert the Text property of a TextBox to a string. It is already a String.
I had to guess at the OleDbType for the parameters. Check your database. It is important to note that the order that parameters appear in the sql command text must match the order that they are added to the parameters collection. Access does not consider the name of the parameter, only the position.
I assume you can retrieve the user's ID when they log in to create flash cards. When the user logs in to use there flash cards you would do something like Select * From Flashcards Where LoginID = #UserID;.
Private Sub btnCreateFlashcard_Click(sender As Object, e As EventArgs) Handles btnCreateFlashcard.Click
Try
InsertFlashcard()
MsgBox("You have successfully added the flashcard into your deck!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub InsertFlashcard()
Dim pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=Path to login.accdb"
Dim Command = " insert into Flashcards (LoginID, [Front],[Back]) values (#Id, #Front, #Back);"
Using myconnection As New OleDbConnection(pro),
cmd As New OleDbCommand(Command, myconnection)
cmd.Parameters.Add("#UserID", OleDbType.Integer).Value = ID
cmd.Parameters.Add("#Front", OleDbType.VarChar).Value = txtFront.Text
cmd.Parameters.Add("#Back", OleDbType.VarChar).Value = txtBack.Text
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
EDIT
As per comment by ADyson I have added code to retrieve ID. Of course in your real application you would be salting and hashing the password. Passwords should never be stored as plain text.
Private ID As Integer
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
Dim pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=Path to login.accdb"
Using cn As New OleDbConnection(pro),
cmd As New OleDbCommand("Select LoginID From login Where Username = #Username and Password = #Password;")
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = txtUserName.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = txtPassword.Text
cn.Open()
Dim result = cmd.ExecuteScalar
If Not result Is Nothing Then
ID = CInt(result)
Else
MessageBox.Show("Invalid Login")
End If
End Using
End Sub

Login form in VB.NET doesn't allow user to login after they've entered login details incorrectly before entering the correct login details

I have a multi-level access login form made in VB.NET that uses an Access database in the back end.
If the user tries to log in when there is nothing entered in either of the text boxes (presses the log in button with nothing entered into either of the text boxes) and then tries to log in after entering their correct details, it allows it.
However, when the user enters either the username or password wrong, it will not allow them to log in after they have entered the correct details.
I am also having a problem where there is no case sensitivity (as long as the password has the correct characters in the correct order it doesn't matter if it is in upper case or lower case).
Imports System.Data.OleDb
Public Class frmLogin
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
Private Sub btnLogIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogIn.Click
If txtUsername.Text = "" Or txtPass.Text = "" Then
lblErrorEmpty.Visible = True
Else
Try
DBCon.Open()
Using cmd As New OleDbCommand("SELECT * FROM tblEmployees WHERE [Username] = #Usernname AND [Pass] = #Pass", DBCon)
cmd.Parameters.AddWithValue("Username", OleDbType.VarChar).Value = txtUsername.Text.Trim
cmd.Parameters.AddWithValue("Pass", OleDbType.VarChar).Value = txtPass.Text.Trim
Dim DBDA As New OleDbDataAdapter(cmd)
Dim DT As New DataTable
DBDA.Fill(DT)
If DT.Rows(0)("Type") = "Manager" Then
frmHomeManager.Show()
ElseIf DT.Rows(0)("Type") = "Receptionist" Then
frmHomeReceptionist.Show()
End If
End Using
Catch ex As Exception
lblErrorMatch.Visible = True
End Try
End If
End Sub
Thank you for your time :)
Don't declare connections outside of the method where they are used. Connections need to be closed and disposed. Using...End Using blocks handle this even when there is an error.
I have separated the user interface code from the database code. This makes the code easier to maintain
For OleDb the .Add method for parameters will help. Don't open the connection until directly before the .Execute. You are only retrieving a single piece of data so .ExecuteScalar should do the trick.
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\NewHotel.mdb;"
Private Sub btnLogIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogIn.Click
If txtUsername.Text = "" OrElse txtPass.Text = "" Then
MessageBox.Show("Please fill in both User Name and Password")
Exit Sub
End If
Dim UserType As Object
Try
UserType = GetUserType(txtUsername.Text.Trim, txtPass.Text.Trim)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If UserType Is Nothing Then
MessageBox.Show("No record found")
ElseIf UserType.ToString = "Manager" Then
frmHomeManager.Show()
ElseIf UserType.ToString = "Receptionist" Then
frmHomeReceptionist.Show()
Else
MessageBox.Show($"{UserType} is not listed.")
End If
End Sub
Private Function GetUserType(UserName As String, Password As String) As Object
Dim Type As Object
Using DBCon As New OleDb.OleDbConnection(ConStr),
cmd As New OleDbCommand("SELECT Type FROM tblEmployees WHERE [Username] = #Usernname AND [Pass] = #Pass", DBCon)
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = UserName
cmd.Parameters.Add("#Pass", OleDbType.VarChar).Value = Password
DBCon.Open()
Type = cmd.ExecuteScalar.ToString
End Using
Return Type
End Function
Your check for the password is case insensitive, because you are storing the password directly and the database is case insensitive.
Your major problem is that you shouldn’t be storing the password in the database, you should be storing a cryptographically secure hash of the password in the database. This will require more work, but will be much safer.
You don’t have enough details to say why you can’t make a second attempt. I will say for reading a single record, I wouldn’t use a data table.

ID already Exist vb.net

I have a code where I want it to update my table and check if there is EmployeeID that is already existing as well. In this picture, I already create a sample EmployeeID but whenever I want it to update, the message box Employee ID already exist interfere. I tried a lot of codes but being a beginner makes it hard for me this is my code to the button Update: Any Help would be Appreciated thank you!
Private Sub BtnUpdate_Click_1(sender As Object, e As EventArgs) Handles btnUpdate.Click
If tbxFname.Text = "" Or tbxLname.Text = "" Then
MessageBox.Show("Please Enter required fields!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Using connection As New SqlConnection(connString)
connection.Open()
Dim com As New SqlCommand("select * FROM [EmmeSubic].[dbo].[UserDetails] WHERE EmployeeID = #employeeID", connection)
com.Parameters.AddWithValue("#employeeID", tbxEmployeeId.Text)
Dim reader As SqlDataReader = com.ExecuteReader
If reader.HasRows Then
MsgBox("Employee Id is Already Exist!!")
Else
connection.Close()
db.SaveChanges()
MessageBox.Show("Your Update has been Saved Successfully!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Using
End Sub`
I think you need to have a look at your database. Be sure primary key is set.

VB.Net - Inserting data to Access Database using OleDb

Can you please tell me what's wrong with the code I'm using? Everytime I execute this, it throws the exception (Failed to connect to database)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb"
Dim sql As String = String.Format("INSERT INTO login VALUES('{username}','{password}','{secques}','{secans}')", txt_username.Text, txt_passwd.Text, txt_secquestion.Text, txt_secansw.Text)
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim icount As Integer = sqlCom.ExecuteNonQuery
MessageBox.Show(icount)
MessageBox.Show("Successfully registered..", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As Exception
MessageBox.Show("Failed to connect to Database..", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
cmd_submit2_Click(sender, e)
End If
End Sub
I am using Access 2013 and VS 2015 Community, if that helps. Thank you.
You should use a parameterized approach to your commands.
A parameterized query removes the possibility of Sql Injection and you will not get errors if your string values are not correctly formatted.
Note that if you don't do anything in the exception block then it is better to remove it and let the exception show itself or at least show the Exception.Message value, so you are informed of the actual error.
Finally every disposable object should be created with the Using statement that ensures a proper close and dispose of such objects (in particular the OleDbConnection)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sql As String = "INSERT INTO login VALUES(#name, #pass, #sec, #sw)"
Using conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb")
Using sqlCom = New System.Data.OleDb.OleDbCommand(sql, conn)
conn.Open()
sqlCom.Parameters.Add("#name", OleDbType.VarWChar).Value = txt_username.Text
sqlCom.Parameters.Add("#pass", OleDbType.VarWChar).Value = txt_passwd.Text
sqlCom.Parameters.Add("#sec", OleDbType.VarWChar).Value = txt_secquestion.Text
sqlCom.Parameters.Add("#sw", OleDbType.VarWChar).Value = txt_secansw.Text
Dim icount As Integer = sqlCom.ExecuteNonQuery
End Using
End Using
End Sub
Keep in mind that omitting the field names in the INSERT INTO statement requires that you provide values for every field present in the login table and in the exact order expected by the table (So it is better to insert the field names)
For example, if your table has only the 4 known fields:
Dim sql As String = "INSERT INTO login (username, userpass, secfield, secfieldsw) " & _
"VALUES(#name, #pass, #sec, #sw)"

System Lock after failed login attempts in VB.net

I use this code for my login form:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim ErrorCount As Integer = 0
If (ErrorCount = 3) Then
MessageBox.Show(" The System has been Lock ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
Form3.Show()
Else
Dim con As OleDbConnection = New OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= UserPass.mdb;")
con.Open()
Dim str As String
str = "SELECT * FROM UserPass WHERE Username='" & txtUsername.Text & "' AND Password='" & txtPassword.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.AddWithValue("user", txtUsername.Text)
cmd.Parameters.AddWithValue("pass", txtPassword.Text)
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
' It will be case sensitive if you compare usernames here.
If sdr.HasRows Then
If sdr.Read Then
If txtPassword.Text <> sdr("Password").ToString Or txtUsername.Text <> sdr("Username").ToString Then
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
ErrorCount = ErrorCount + 1
Else
MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
frmOne.Show()
Me.Hide()
End If
End If
Else
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
sdr.Close()
con.Close()
End If
What im trying to do is when the user fails to login to the system 3 times, the system will show another form that says the system is locked and the user needs to type in the password from the system to be able to try to log-in again. Kindly help please.
im using ms access as database for the username and password
Combination of two of the other answers. You need to change the declaration to static so that it maintains state. Dim ErrorCount As Integer = 0 to Static ErrorCount As Integer
You also need to add a decrement to the code path where the user has entered an invalid username.
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
ErrorCount = ErrorCount + 1 'add this here
Then move the if so that it is after the SQL so move this to after con.close()
If (ErrorCount = 3) Then
MessageBox.Show(" The System has been Lock ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
Form3.Show()
Else
Also you seem to have some confusion about parameterized queries. If your using parameterized queries then you don't need to concatenate your SQL which should be
str = "SELECT * FROM UserPass WHERE Username=#user AND Password=#pass"
Also the inside if should never be true under normal conditions
If txtPassword.Text <> sdr("Password").ToString Or txtUsername.Text <> sdr("Username").ToString Then
' this code path is only evaluated if the database ignores the where clause or
' the user changes the username or password textboxs whilst the database connection is proccessing and is therfore unnessacary
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
ErrorCount = ErrorCount + 1
Else
MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
frmOne.Show()
Me.Hide()
End If
Finally don't store passwords as plaintext. Use a hash from the System.Security.Cryptography namespace with a salt.
I'm not entirely sure that I understand the question. But this part makes it sound to me like you are trying to lock the computer's entire desktop after a logon attempt in your program has failed three times:
What im trying to do is when the user fails to login to the system 3 times, the system will show another form that says the system is locked and the user needs to type in the password from the system to be able to try to log-in again.
I'm not sure that's a good idea. Wouldn't it be sufficient just to lock the user out of your program instead of locking the entire computer? Think of it like this: there's no reason to inflict a global punishment for a local infraction.
But, putting aside whether or not I think it's a good idea, it's perfectly do-able from VB.NET. All you need to do is call the LockWorkStation function after your counter indicates that three failed login attempts have occurred. This function is provided as part of the Win32 API, so to call it directly from a .NET application, you'll need to use P/Invoke. This function has a relatively simple signature, so its definition shouldn't be too hard to understand either:
<DllImport("user32.dll", SetLastError=True)> _
Public Shared Function LockWorkStation() As Boolean
End Function
This function has some important constraints on its use, namely that it can only be called by processes that are running on the interactive desktop. This is not a problem for you, though, since you're building a GUI application that can only run on the interactive desktop, and you know that if someone has entered an invalid password three times, they're definitely logged in and sitting a few feet from the keyboard.
Invoking the magic from your code is relatively simple, although it's possible for the function to fail and you should handle those error conditions (lest someone find a security backdoor into your application):
If (FailedLogonAttempts < 3) Then
' Do whatever...
Else
' Lock 'em out!
Dim success As Boolean = LockWorkstation()
If Not success Then
' Uh-oh! An error occurred! You need to handle this, otherwise someone
' might be able to gain unauthorized access to the system.
'
' For demonstration and debugging purposes, we'll throw an exception,
' but that's obviously not a secure long-term solution.
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
End If
If you're just asking how to fix your existing code, the problem is that your ErrorCode variable never goes beyond 0. You've declared it at the top of the btnLogin_Click method like so:
Dim ErrorCount As Integer = 0
That's as a regular variable with method-level scope. That means it is re-initialized (to 0, like you ask it to be) every time that the method runs and does not retain its value.
If you want to declare a variable with method-level scope that does retain its value, you need to declare the variable using the Static keyword, like so:
Static ErrorCount As Integer = 0
A great way to test these things, and figure out what's wrong, is to set a breakpoint inside of the btnLogin_Check method and see exactly what values the variables have! If you did that, you'd notice that each time, ErrorCount is set to 0 after execution passes over the first line. That would be your immediate clue as to what the problem is. Then you just have to figure out how to make the value stick. Now you know you do it using the Static keyword (or moving up a scope, like making it a member of your Form class so that it lives as long as objects of that class).
You can try something like this:
Dim ErrorCount As Int = 0
If (ErrorCount =3) Then
MessageBox.Show(" The System has been Lock ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Do stuff
'Add Your Code to show new Form something like
Me.Hide()
Form3.Show()
Else
Dim con As OleDbConnection = New OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= UserPass.mdb;")
con.Open()
Dim str As String
str = "SELECT * FROM UserPass WHERE Username='" & txtUsername.Text & "' AND Password='" & txtPassword.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.AddWithValue("user", txtUsername.Text)
cmd.Parameters.AddWithValue("pass", txtPassword.Text)
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
' It will be case sensitive if you compare usernames here.
If sdr.HasRows Then
If sdr.Read Then
If txtPassword.Text <> sdr("Password").ToString Or txtUsername.Text <> sdr("Username").ToString Then
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
ErrorCount = ErrorCount + 1
Else
MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
frmOne.Show()
Me.Hide()
End If
End If
Else
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
sdr.Close()
con.Close()
End If
Best Regards
Imports System.Data.OleDb
Public Class Form1
Private attempt As Integer = 3
Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
Dim cn As New OleDbConnection("Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\testing.Accdb;")
cn.Open()
If txtpassword.Text = "" Then
MsgBox("Please Enter Your Password !!!", MsgBoxStyle.Critical, "Attention...")
Exit Sub
End If
Dim dr1 As OleDbDataReader
Dim com1 As New OleDbCommand
com1.CommandText = "select [UserID],[Pass] from userinfo where userid = '" & txtUserID.Text & "'"
com1.Connection = cn
If cn.State = ConnectionState.Closed Then cn.Open()
dr1 = com1.ExecuteReader
If dr1.Read Then
If UCase(dr1("Pass")) = UCase(txtpassword.Text) Then
MessageBox.Show("Welecome")
Me.Close()
Else
MessageBox.Show("Wrong Password [" & attempt - 1 & "] Attempt(s) Remaing")
attempt -= 1
txtpassword.Focus()
If attempt = 0 Then
End
End If
End If
Exit Sub
Else
MessageBox.Show("Wrong UserID [" & attempt - 1 & "] Attempt(s) Remaing")
attempt -= 1
txtpassword.Focus()
If attempt = 0 Then
End
End If
End If
cn.Close()
End Sub
Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
End
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Me.Dispose()
End Sub
End Class