Okay I have created a log in system on VB.net using a database on access. The problem I am having is that some of the username and password combinations work perfectly, but some of them, although put in correctly, don't work at all. This is the code I have written...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Check if username or password is empty
If textpassword.Text = "" Or textusername.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields were supplied
' Check if user exist in database
' Connect to DB
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\database1.accdb"
'conn.Open()
'MsgBox("Susscess")
Dim sql As String = "SELECT * FROM Accounts WHERE username='" & textusername.Text & "' AND password = '" & textpassword.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then
MemberPage.Show()
Me.Hide()
Else
' If user enter wrong username and password combination
' Throw an error message
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
'Clear all fields
textpassword.Text = ""
textusername.Text = ""
'Focus on Username field
textusername.Focus()
End If
End If
End Sub
Do not Concatenate string.Its wide open for SQL injection .Its better to use Parameterized query
Dim sql As String = "SELECT * FROM Accounts WHERE username=? AND password = ?"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
sqlCom.Parameters.AddWithValue("?", textusername.Text);
sqlCom.Parameters.AddWithValue("?", textpassword.Text);
Also you can use HasRows property
If sqlRead.HasRows Then
While sqlRead.Read()
MemberPage.Show()
Me.Hide()
End While
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) 'Clear all fields
textpassword.Text = ""
textusername.Text = ""
'Focus on Username field
textusername.Focus()
End If
It seems that some mistake is happening at the condition you checking after filling the dataReader. i.e
If sqlRead.Read() Then
try the if condition by following code
If Not sqlRead Is Nothing Then
if it doesnt work then..
I would suggest you to do it using DataAdapter and check whether it returns rows. if the row count is greater than 1 , you must show the MemberPage
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If textpassword.Text = "" Or textusername.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\database1.accdb"
Dim sql As String = "SELECT * FROM Accounts WHERE username='" & textusername.Text & "' AND password = '" & textpassword.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
Dim ds As DataSet
sqlCom.Connection = conn
conn.Open()
'Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
Dim da as New OleDbDataAdapter(sqlCom)
da.Fill(ds)
If ds.Tables(0).Rows.Count > 1 Then
MemberPage.Show()
Me.Hide()
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
textpassword.Text = ""
textusername.Text = ""
textusername.Focus()
End If
End If
End Sub
Related
How would I be able to only allow existing users from a MS access database to login. I have a MS database and the 3 attributes "AccountID", "Username" and "Password"
My database: Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Desktop\ProjectDatabase.accdb
Private Sub Loginbtn_Click(sender As Object, e As EventArgs) Handles Loginbtn.Click
If Usernamebtn.Text = "Admin" AndAlso Passwordbtn.Text = "code" Then
MsgBox("You are Logged In!", MessageBoxIcon.Information, "Login")
AppMenu.Show()
Me.Hide()
ElseIf Usernamebtn.Text = "" OrElse Passwordbtn.Text = "" Then
MsgBox("Please Fill in the Username and Password!", MsgBoxStyle.Critical, "Error")
Else
If Usernamebtn.Text = My.Settings.Username AndAlso Passwordbtn.Text = My.Settings.Password Then
MsgBox("You are Logged In!", MessageBoxIcon.Information, "Login")
AppMenu.Show()
Me.Hide()
Else
MsgBox("User dosen't exist OR password incorrect, Please try again.", MsgBoxStyle.Critical, "Error")
End If
End If
End Sub
You should save user information in database. Every time a user logs in, it's information will be compared with the data in database.
Here's an simple example you can refer to.
Design view of my table:
Code:
Private connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= your file path;"
Private Sub Loginbtn_Click(sender As Object, e As EventArgs) Handles Loginbtn.Click
Using conn As OleDbConnection = New OleDbConnection(connString)
conn.Open()
Dim cmdTxt As String = "SELECT password FROM UserTable WHERE username = #username"
Using cmd As OleDbCommand = New OleDbCommand(cmdTxt, conn)
cmd.Parameters.AddWithValue("username", UsernameTxt.Text)
Dim reader = cmd.ExecuteReader
If reader.HasRows Then
While reader.Read
Dim pwd As String = reader(0).ToString
If PasswordTxt.Text.Equals(pwd) Then
MsgBox("You are Logged In!", MessageBoxIcon.Information, "Login")
Else
MsgBox("Your username or password is incorrect, Please try again.", MsgBoxStyle.Critical, "Error")
End If
End While
Else
MsgBox("Your username or password is incorrect, Please try again.", MsgBoxStyle.Critical, "Error")
End If
End Using
End Using
End Sub
I am trying to make a query that deletes the user from my database.
But when i confirm to delete the user it gives me an error:
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "#Username".
Imports System.Data.SqlClient
Public Class DeleteForm
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim RetVal As Integer
Dim conn = New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbProject;Integrated Security=True")
Using cmd = New SqlCommand("select count(*) from tblLogin where username = #Username and password = #Password", conn)
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text
conn.Open()
If conn.State = ConnectionState.Open Then
RetVal = CInt(cmd.ExecuteScalar)
If RetVal = 1 Then
If txtPassword.Text And txtCheckPassword.Text <> "" Then
If txtCheckPassword.Text = txtPassword.Text Then
Dim cancConf As Integer = MessageBox.Show("This cant be undone!" & vbCrLf & "Are you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If cancConf = DialogResult.Yes Then
Try
Dim queryDelete As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdDelete As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.ExecuteNonQuery()
MsgBox("Account deleted succesfully!")
cmdCancellazione.Dispose()
conn.Close()
LoginForm.Show()
Me.Close()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
ElseIf cancConf = DialogResult.No Then
End If
Else
MsgBox("The passwords arent matching!", MsgBoxStyle.Exclamation)
End If
ElseIf txtPUtenteCANC.Text <> "" And txtPUtenteCONF.Text = "" Then
MsgBox("Please, confirm the password")
End If
Else
MsgBox("User not found!", MsgBoxStyle.Exclamation)
txtNUtenteCANC.Clear()
txtPUtenteCANC.Clear()
txtPUtenteCONF.Clear()
txtNUtenteCANC.Select()
End If
Else
MessageBox.Show("The connection is not open!" & vbCrLf & "The program will close", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End
End If
End Using
End Sub
End Class
You have added that parameter to the SELECT COUNT command but not to the DELETE command.
Dim queryCancellazione As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdCancellazione As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
If CbDept_login.Text = "DEPT1" Then
Dim con As New SqlConnection("Data Source=XYZ-PC;Database=DATABASE1;Integrated Security =true")
con.Open()
Dim rs As New SqlCommand("SELECT * FROM TABLE1 WHERE Username=#Username COLLATE SQL_Latin1_General_CP1_CS_AS AND Password=#Password COLLATE SQL_Latin1_General_CP1_CS_AS", con)
Dim UsernameParam As New SqlParameter("#Username", Me.txtUsername.Text)
Dim PasswordParam As New SqlParameter("#Password", Me.txtPassword.Text)
rs.Parameters.Add(UsernameParam)
rs.Parameters.Add(PasswordParam)
Dim sqlRead As SqlDataReader = rs.ExecuteReader
If sqlRead.HasRows Then
If sqlRead.Read = True Then
If sqlRead("UserType") = "Admin" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_Admin.Show()
frm_Admin.LblLogAsAdmin_LCR.Text = txtUsername.Text
Me.Close()
ElseIf sqlRead("UserType") = "Staff" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_User.Show()
frm_User.TblogAsuser.Text = txtUsername.Text
Me.Close()
End If
End If
Else
MsgBox("Please input correct username and password", MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical, "Login Failed")
txtPassword.Text = ""
con.Close()
End If
End If
If CbDept_login.Text = "DEPT2" Then
Dim conn As New SqlConnection("Data Source=XYZ-PC;Database=DATABASE2;Integrated Security =true")
conn.Open()
Dim rs As New SqlCommand("SELECT * FROM TABLE2 WHERE Username=#Username COLLATE SQL_Latin1_General_CP1_CS_AS AND Password=#Password COLLATE SQL_Latin1_General_CP1_CS_AS", con)
Dim UsernameParam As New SqlParameter("#Username", Me.txtUsername.Text)
Dim PasswordParam As New SqlParameter("#Password", Me.txtPassword.Text)
rs.Parameters.Add(UsernameParam)
rs.Parameters.Add(PasswordParam)
Dim sqlRead As SqlDataReader = rs.ExecuteReader
If sqlRead.HasRows Then
If sqlRead.Read = True Then
If sqlRead("UserType") = "Admin" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_Admin.Show()
frm_Admin.LblLogAsAdmin_LCR.Text = txtUsername.Text
Me.Close()
ElseIf sqlRead("UserType") = "Staff" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_User.Show()
frm_User.TblogAsuser.Text = txtUsername.Text
Me.Close()
End If
End If
Else
MsgBox("Please input correct username and password", MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical, "Login Failed")
txtPassword.Text = ""
conn.Close()
End If
End If
End Sub
Hello, I'm currently facing a problem in my vb project. I'm using visual studio 2012 and SQL server 2012 for my database. I have a login form in which you can access to the different databases just by choosing department name in a combo box and it will check if you input a correct username and password using sqldatareader depends on the username and password value on the database of the department that you choose. Now my problem is when I run it, it will show an error "No source available". maybe my codes are wrong, please help me. thank you in advance. By the way, i put this code on my Login Button.
Hello guys am having issues with my login form for multiple users of my software, below is the complete login button code for the admin
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
If cmbusertype.Text = "" Then
MsgBox("Please select the appropriate Account Type!", vbExclamation, "Account Type")
End If
If cmbusertype.Text = "Admin" Then
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Selectcmd As String = "select * from tbl_admin where admin_username = '" + txtusername.Text + "' and password = '" + txtpassword.Text + "'"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Selectcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
da.Fill(ds)
Matching Admin User Name & Password
If ds.Tables(0).Rows.Count > 0 Then
If txtusername.Text = ds.Tables(0).Rows(0).Item(0) And txtpassword.Text = ds.Tables(0).Rows(0).Item(1) Then
MsgBox("Administrator Log-in Successful.", vbInformation, "Admin Log-in")
Me.Hide()
adminform.Show()
Else
ErrorProvider1.SetError(txtusername, "Invalid User Name.")
ErrorProvider1.SetError(txtpassword, "Invalid Password.")
MsgBox("Invalid Administrator Username or Password.", vbCritical, "Admin Log-in")
End If
Else
ErrorProvider1.SetError(txtusername, "Invalid User name or Password.")
ErrorProvider1.SetError(txtpassword, "Invalid User name or Password.")
ErrorProvider1.SetError(cmbusertype, "Please select the appropriate Account Type")
MsgBox("Invalid Administrator Username or Password.", vbCritical, "Admin Log-in")
End If
End If
End Sub
the code line highlighted is the following
If txtusername.Text = ds.Tables(0).Rows(0).Item(0) And txtpassword.Text = ds.Tables(0).Rows(0).Item(1) Then
and the error is "Conversion from string "admin" to type 'Double' is not valid." am actually new to vb trying to create a login for multiple users, the above part as you can see is just for the admin. Please any help here will be appreciated thanks.
Try this...
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
If cmbusertype.Text = "" Then
MsgBox("Please select the appropriate Account Type!", vbExclamation, "Account Type")
End If
If cmbusertype.Text = "Admin" Then
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Selectcmd As String = "select * from tbl_admin where admin_username = #usernme and password = #paswd"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Selectcmd, sqlconn)
sqlcmd.parameters.addwithValue("#usernme",txtusername.Text)
sqlcmd.parameters.addwithValue("#paswd",txtpassword.Text)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
da.Fill(ds)
I'm using this code and every time I press the loginBTN where my code are nothing happens im done with connecting in the server which is SQL Server
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loginbtn.Click
Dim username As String
Dim password As String
Dim password1 As String
Dim oleConn As New SqlConnection(main.conString)
oleConn.Open()
Try
Dim login As String = "Select *from admin where username = '" & usernametxt.Text & "' AND password = '" & passwordtxt.Text & "' "
Dim command As New SqlDataAdapter(login, oleConn)
Dim command1 As New SqlCommand(login, oleConn)
Dim reader1 As SqlDataReader = command1.ExecuteReader()
If reader1.HasRows Then
While reader1.Read
username = reader1("username")
password = reader1("password")
password1 = passwordtxt.Text()
If username = usernametxt.Text And password = password1 Then
main.Show()
Me.Hide()
End If
End While
Else
PictureBox1.Show()
errorLabel.Show()
Beep()
'MsgBox("wrong password or username")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
oleConn.Close()
End Try
End Sub