How To Make Log In system Using vb.net and SQL Server - sql-server

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

Related

How to get rid of Conversion from string "admin" to type 'Double' is not valid

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)

Can someone check over my VB.net code? Issue explained below

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

"There is no row at position 0"?

Private Sub BtnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLogin.Click
Dim sql As String
sql = " SELECT * FROM LoginDetails WHERE UsernameID = '" & TxtUsername.Text & "' AND Password = '" & TxtPassword.Text & "'"
ds = db.sqlSelect(sql)
Dim i As Integer
Dim Username As String = ds.Tables("LoginDetails").Rows(i)("UsernameID")
Dim Password As String = ds.Tables("LoginDetails").Rows(i)("Password")
''''''STUDENT LOGIN'''''''
If TxtUsername.Text = "" And TxtPassword.Text = "" Then
MsgBox("No username and password entered!")
ElseIf TxtUsername.Text = "" Then
MsgBox("No username entered!")
ElseIf TxtPassword.Text = "" Then
MsgBox("No password entered!")
End If
Username = TxtUsername.Text.ToLower
Password = TxtPassword.Text.ToLower
If TxtUsername.Text.ToLower = Username And TxtPassword.Text = Password Then
FrmMainMenu.Show()
Me.Hide()
FrmMainMenu.LblWelcome.Text = "Welcome " & ds.Tables("LoginDetails").Rows(i)("Student Name") & "!"
ElseIf TxtUsername.Text.ToLower = Username And TxtPassword.Text <> Password Then
MsgBox("Wrong password entered!")
End If
If TxtUsername.Text.ToLower <> Username And TxtPassword.Text <> Password Then
MsgBox("Wrong password or username!")
Else
End If
If Len(Username) <> 7 Then
MsgBox("Username must be exactly 7 characters long and must be in the following format: 1XlXXXX")
End If
If Len(Password) < 6 And Len(Password) > 30 Then
MsgBox("Password must be between 6 and 30 characters!")
End If
When I type in the correct details for the form it works, but whenever I type in say a wrong password, it crashes!
Can anyone help me solve this?? I keep getting this error!!!
IndexOutofRangeException was unhandled
There is no row at position 0.
Pointing at the code: Dim Username As String = ds.Tables("LoginDetails").Rows(i)("UsernameID")
Here is the class that links the code to my database:
Imports System.Data.OleDb
Public Class clsDBConnector
Dim con As New OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Sub connect()
dbProvider = "PROVIDER=MICROSOFT.ACE.OLEDB.12.0;"
dbSource = "Data Source = E:\Computing\COMP4\Database.accdb "
con.ConnectionString = dbProvider & dbSource
con.Open()
End Sub
Function sqlSelect(ByVal sqlString As String)
da = New OleDbDataAdapter(sqlString, con)
da.Fill(ds, "LoginDetails")
Return ds
End Function
Sub reset()
ds.Reset()
End Sub
Sub SQLinsert(ByVal sql) 'inserts data into database
Dim da As New OleDbCommand(sql, Con)
da.ExecuteNonQuery()
End Sub
Function SQLupdate(ByVal sqlString As String)
da = New OleDbDataAdapter(sqlString, con)
da.Fill(ds, "LoginDetails")
Return ds
End Function
End Class
The first thing you're doing wrong is storing plain-text passwords. Never store plain-text passwords.
The second thing is that you're wide open to SQL injection attack. Use parameterized queries. Otherwise you're allowing users to arbitrarily execute any code they'd like on your database.
The third thing is that you're assuming a returned value here:
sql = " SELECT * FROM LoginDetails WHERE UsernameID = '" & TxtUsername.Text & "' AND Password = '" & TxtPassword.Text & "'"
ds = db.sqlSelect(sql)
Dim i As Integer
Dim Username As String = ds.Tables("LoginDetails").Rows(i)("UsernameID")
Dim Password As String = ds.Tables("LoginDetails").Rows(i)("Password")
If that SELECT statement doesn't find any values, then Rows(i) (i is 0 in this case since that's the default for an Integer) doesn't exist. You need to check the count of Rows before trying to access it. In this case, logically, if Rows.Count is 0 then no match was found for the username/password combination, so the login fails. Notify the user that the login has failed and stop executing anything else.
The fourth thing you're doing wrong is storing plain-text passwords. Never store plain-text passwords.
Before you start using the dataset after the SQL call you should alway check to see if you received valid/any data back . Call a DataSet check method like the one I included. If it returns false you know your SQL returned an empty DataSet. So you can display a message stating invalid login info..
bool IsEmpty(DataSet dataSet)
{
foreach(DataTable table in dataSet.Tables)
{ if (table.Rows.Count != 0) return false; }
return true;
}
Every time you try to take information from the DB, with something like:
If ds.tables("MyTable").rowsCount > 0 then
// Do the stuff
Else
// There is no information on the table
End If

How to check if a record exists in an Access database

I'm trying a new approach for a project that I'm working on and I'm just starting to learn about Access Databases. I using VB.net and my question is: How do you see if a record exists in the table of the database. I thought I had it understood but that is not the case. I'm creating a login and I want it to check if the Username that they typed in exists before it tries to compare what you typed with what's in the database. I see alot of questions on how to do this...but not for VB.net and MS Access
Here's my code:
Imports System.Data.OleDb
Public Class LoginForm1
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim Errors As String
Public Sub AccessAccountDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
Try
myConnection.Open()
Dim str As String
str = "SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & "' AND Password='" & PasswordTxt.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
myConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OkayBtn_Click(sender As System.Object, e As System.EventArgs) Handles OkayBtn.Click
AccessAccountDatabase()
End Sub
End Class
So now my question is... How do you get it to check if a record exists in the database, because when you type in the correct information (The correct username and password that exists in the database) it says welcome and all. But when you type in the wrong Username and/or Password it doesn't work. Without the "Try Catch" statement the program just freezes. With the try catch it states this:
System.InvalidOperationException: No data exists for the row/column.
at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.get_Item(String name)
at CybSol_Journal_Database.LoginForm1.AccessAccountDatabase() in c:\users\richard\documents\visual studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\LoginForm1.vb:line 36
Addition information: line 36 is this: If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
First problem:
PASSWORD is a reserved keyword in Access. You should encapsulate in square brackets:
"SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & _
"' AND [Password]='" & PasswordTxt.Text & "'"
Second problem:
NEVER use string concatenation to create sql text. ALWAYS use parameters
str = "SELECT * FROM Accounts WHERE Username=? AND [Password]=?"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("user", UserNameTxt.Text)
cmd.Parameters.AddWithValue("pass", PasswordTxt.Text)
dr = cmd.ExecuteReader
Why? look here what could happen if you concatenate strings from user input
Third problem: Test if your command returns rows
If dr.Read() Then
......
End if
I added some Using statements so you don't have to manually close the connections. Also, I parameterized the SQL statement to prevent SQL Injection.
Public Class LoginForm1
Dim provider As String
Dim dataFile As String
Dim connString As String
'Public myConnection As OleDbConnection = New OleDbConnection
'Public dr As OleDbDataReader
Dim Errors As String
Public Sub AccessAccountDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
Try
Using myConnection As OleDbConnection = New OleDbConnection(connString)
myConnection.Open()
Dim str As String
str = "SELECT * FROM Accounts WHERE Username=#USER AND [Password]=#PWD "
Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#USER", UsernameTxt.Text)
cmd.Parameters.AddWithValue("#PWD", PasswordTxt.Text)
Using dr As OleDbDataReader = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
Else
MsgBox("Login Failure")
End If
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OkayBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OkayBtn.Click
AccessAccountDatabase()
End Sub
End Class
You're on the right track. The OleDbDataReader.Read returns a boolean indicating whether or not it successfully read an existing row. Therefore, you can check to see if it returned True before trying to read the record. For instance:
If dr.Read() Then
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
End If
Also, I feel I should at least mention that storing a password in plain text is never a good idea.
You don't have to check for the username and password in your code again since if does not match in the database, no rows will be returned.
You can simply do
dr = cmd.ExecuteReader
If dr.HasRows Then
//it matched
Else
//it didn't match. could not log in
End If
Your approach is below if you still want to keep it but it's not necessary
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Else
End If
End If
Use the Read() method on your DataReader (note that this keeps your connection to the database open and you'll be unable to execute any other commands on the database while your DataReader is still Reading.
If String.Compare(dr("Username").ToString(), UsernameTxt.Text, true) AndAlso String.Compare(dr("Password").ToString(), PasswordTxt.Text.ToString() Then
' The username and password for the record match
' the input from the login form
ProcessLogin()
Else
' Invalid username or password, send an error
End If

Exception causing VB.NET code to not run properly

I am getting an exception when I run the below VB.NET code to validate a user..The exception says that "Incorrect syntax near variable user"
Can anyone tell me where am I going wrong ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text.Trim().Length = 0 Or TextBox2.Text.Trim().Length = 0 Then
MsgBox("Enter a user id and password")
Return 'Terminate this method
End If
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim userid = TextBox1.Text
Dim password = TextBox2.Text
Try
myconnection = New SqlConnection("server=PARTH- PC\SQLEXPRESS;uid=sa;pwd=parth;database=fcrit")
myconnection.Open()
mycommand = New SqlCommand("select * from user where [user id]=#userid and [password]=#password", myconnection)
mycommand.Parameters.Add("#userid", SqlDbType.VarChar, 30).Value = userid
mycommand.Parameters.Add("#password", SqlDbType.VarChar, 30).Value = password
'mycommand = New SqlCommand("select * from user where user id='" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", myconnection)
dr = mycommand.ExecuteReader()
If (dr IsNot Nothing) Then
If (dr.Read()) Then
MsgBox("User is authenticated")
Form2.Show()
Else
MsgBox("Please enter correct username and password")
End If
End If
myconnection.Close()
Catch ex As Exception
Throw
Finally
End Try
End Sub
Try changing your SQL to -
"select * from [user] where [user id]=#userid and [password]=#password"
According to this page 'User' is a reserved word
User is a reserved word in SQL Server.
Put brackets around the table name:
mycommand = New SqlCommand("select * from [user] where [user id]=#userid and [password]=#password", myconnection)

Resources