Selecting radiobuttons from database? - vb.net

I would like my database to also select radiobuttons from my access database. However whenever I try running my program and providing the needed information, an error shows up
" Error:Syntax error in string in query expression 'username=asjjm'
AND password = 'ksjadklf' AND facultymember = 'False' AND student =
'False. "
I don't really understand errors like that because I'm only a beginner. Can someone tell me whats wrong? Thank you very much.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
' Check if username or password is empty
If TxtPassword.Text = "" Or TxtUsername.Text = "" Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields was supply
' 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=C:\Thesis\Thesis\Database2.accdb"
Try
'conn.Open()
'MsgBox("Susscess")
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TxtUsername.Text & "' AND password = '" & TxtPassword.Text & "' AND facultymember = '" & RadioButton1.Checked & "' AND student ='" & RadioButton2.Checked '""
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
MainStud.Show()
Me.Hide()
Else
' If user enter wrong username and password combination
' Throw an error message
MessageBox.Show("Username, Password, and Account Type do not match!", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
'Clear all fields
TxtPassword.Text = ""
TxtUsername.Text = ""
'Focus on Username field
TxtUsername.Focus()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End If
End Sub
*Edit
I did exactly what #chepe263 said and got two new errors.
End of statement expected
'System.Data.Sql' is a namespace and cannot be used as an expression.
What's causing these? Note* I made the radiobuttons to indicate choices whether the user is logging in on an account as a faculty member or student.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
' Check if username or password is empty
If TxtPassword.Text = "" Or TxtUsername.Text = "" Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields was supply
' 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=C:\Thesis\Thesis\Database2.accdb"
Try
'conn.Open()
'MsgBox("Susscess")
Dim facultyMemberName As String
Dim rbdtext As String
If RadioButton1.Checked Then
facultyMemberName = RadioButton1.Text
End If
If RadioButton2.Checked Then
rbdtext = RadioButton2.Text
End If
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TxtUsername.Text & "' AND password = '" & TxtPassword.Text & "' AND facultymember = '" & facultyMemberName & "' AND student ='" & rbdtext """
Dim sqlCom As New System.Data.OleDb.OleDbCommand(Sql, conn)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then
MainStud.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
TxtPassword.Text = ""
TxtUsername.Text = ""
'Focus on Username field
TxtUsername.Focus()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End If
End Sub
Edit* Still not over this. Tried every possible solution but still shows errors. Sorry if it could get so confusing. I'm just a beginner.

you try something like this
if (RadioButton1.Checked)
{
rbdtext = RadioButton1.Text;
}
else if (RadioButton2.Checked)
{
rbdtext = RadioButton2.Text;
}
else
{
rbdtext = RadioButton3.Text;
}
then your SQL Statement
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TxtUsername.Text & "' AND password = '" & TxtPassword.Text & "' AND facultymember = '" & rbdtext & "' AND student ='" & rbdtext '""

declare a new variable inside Button Click's Private sub
Dim facultyMemberName as String
Do what Parth Akbari suggests
If RadioButton1.Checked Then
facultyMemberName = RadioButton1.Text
End If
(Repeat for as many radio buttons you have)
Then place the right variable name and fix the end of your string (the single quote is before the double quote and it makes it a commentary, no good)
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TxtUsername.Text & "' AND password = '" & TxtPassword.Text & "' AND facultymember = '" & facultyMemberName & "' AND student ='" & rbdtext """
Tips (just opinions)
Try using a ListBox or ComboBox instead of RadioButtons since you are listing names of people. You could do something like
facultyMemberName = lstFacultyName.SelectedItem.Text
Try placing your sql query in a textbox, copy it and run it with your favorite SQL manager. You can detect potential errors that way.
Try using parameters instead of concatenate values to a string.

Related

Login Process Issues

Public Class login
Dim conn As MySqlConnection
Dim Reader As MySqlDataReader
Dim cmd As MySqlCommand
Dim audit As String
Dim faudit As String
Dim connectiontime, active As String
Dim attempts As String
Dim server As String = "server=127.0.0.1;user=root;database=spilibrary"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim statement As String
Dim Userrole As String
conn = New MySqlConnection
conn.ConnectionString = server
conn.Open()
statement = "select * from user where Username = '" & username.Text & "' and Password = BINARY '" & password.Text & "'"
cmd = New MySqlCommand(statement, conn)
Reader = cmd.ExecuteReader
Try
Dim found As Boolean
While Reader.Read
found = True
Userrole = Reader.GetString("Userrole")
connectiontime = Reader.GetString("connectiontime")
attempts = Reader.GetString("attempts")
If Userrole = "Administrator" And connectiontime = "Now" Or connectiontime <= TimeOfDay.ToString("HH:mm") Then
MsgBox("Welcome Admin", MsgBoxStyle.Information, "System message")
mainform.Show()
mainform.Maintenancebtn.Enabled = True
mainform.level1.Text = Userrole
'Me.Close()
Reader.Close()
cmd = New MySqlCommand("update user set attempts = '" & "0" & "', connectiontime='" & "Now" & "' where Username='" & username.Text & "'", conn)
Reader = cmd.ExecuteReader
ElseIf Userrole = "Librarian" And connectiontime = "Now" Or connectiontime <= TimeOfDay.ToString("HH:mm:ss") Then
MsgBox("Welcome Librarian", MsgBoxStyle.Information, "System Message")
'mainform.Maintenancebtn.Enabled = False
mainform.Show()
mainform.level1.Text = Userrole
' Me.Close()
'OPAC.show()
Reader.Close()
cmd = New MySqlCommand("update user set attempts ='" & "0" & "', connectiontime ='" & "Now" & "' where Username='" & username.Text & "'", conn)
Reader = cmd.ExecuteReader
ElseIf Userrole = "Administrator" And connectiontime <> "Now" And connectiontime >= TimeOfDay.ToString("HH:mm:ss") Then
MsgBox("You're Account has been blocked because of multiple failed attempts", vbCritical, "System Message")
ElseIf Userrole = "Librarian" And connectiontime <> "Now" And connectiontime >= TimeOfDay.ToString("HH:mm:ss") Then
MsgBox("Your Account has been blocked because of multiple failed attempts", vbCritical, "System Message")
Else
MsgBox("You're Account whas been blocked because of multiple failed attempts", vbCritical, "System Message")
End If
Someone please help me with this.. when i hit login button it always reads the first if-else statement i enter which is the Userrole="administrator" even if im logging in my Librarian Userrole. when i try to switch them the It reads the librarian userrole and not the admin even if im logging my admin userrole.. in my database they are declared right. so maybe it's the code. Thank you
Try using brackets in your condition to make it clearer. Like this:
If Userrole = "Administrator" AndAlso (connectiontime = "Now" OrElse connectiontime <= TimeOfDay.ToString("HH:mm")) Then
in your code, it would also match if
connectiontime <= TimeOfDay.ToString("HH:mm")

How can I avoid errors around reserved words when querying Access?

I use the code below to log the user into my system:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim LogUsername As String = txtUsername.Text
Dim LogPassword As String = txtPassword.Text
If txtPassword.Text <> "" And txtUsername.Text <> "" Then
cmdLogin.CommandText = "SELECT * FROM [User Query] WHERE Username ='" & CStr(LogUsername) & "' AND Password ='" & CStr(LogPassword) & "'"
cmdLogin.Connection = cnnOledb
Dim DR As OleDbDataReader = cmdLogin.ExecuteReader()
If DR.Read = True Then
If DR(0).ToString = LogUsername And DR(1).ToString = LogPassword Then
'User_ID = DR(2).ToString
MsgBox("Login Succesful!")
End If
Else : MsgBox("Invalid Username or Password, please try again", MsgBoxStyle.Critical + MsgBoxStyle.RetryCancel, "Login Error")
txtUsername.Clear()
txtPassword.Text = ""
End If
DR.Close()
End If
End Sub
After clicking on the login button, an exception is thrown:
The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect
This is the screenshot of the error occur when i click on the Login Button.
This is the screenshot of the table that i am using to do login.
I agree with the comments but the immediate cause of your issue is that "Password" is a reserved word in Access so you need to escape it if you want to use it as an identifier. You already know how to do that because you're already doing it with the table name, which you have poorly named with a space in it.

How can I make this Login case sensitive?

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

Connection is not closed (vb)

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jen\Documents\Jade\vb\database.accdb")
txtAdmin.Text = "Admin"
Dim strsql As New OleDbCommand("select * from Account where Username ='" & txtUsername.Text & "' AND [Password] ='" & txtPassword.Text & "' AND AccountType = '" & txtAdmin.Text & "'", conn)
Dim strsql2 As New OleDbCommand("select * from Account where Username ='" & txtUsername.Text & "' AND [Password] ='" & txtPassword.Text & "' AND AccountType = '" & txtStudent.Text & "'", conn)
Dim uu As New OleDbParameter("UserName", txtUsername.Text)
Dim pp As New OleDbParameter("Password", txtPassword.Text)
strsql.Connection.Open()
strsql2.Connection.Open()
Dim reader As OleDbDataReader
reader = strsql.ExecuteReader
Dim reader2 As OleDbDataReader
reader2 = strsql2.ExecuteReader
If reader.HasRows Then
strsql.Connection.Close()
MsgBox(" Welcome Admin!", vbInformation)
frmIndex.Show()
desktopFade.Close()
ElseIf reader2.HasRows Then
strsql2.Connection.Close()
MsgBox(" Welcome Student!", vbInformation)
frmReg.Show()
desktopFade.Close()
ElseIf txtUsername.Text = "" And txtPassword.Text = "" Then
MsgBox("Don't leave the fields blank", vbCritical)
txtUsername.Focus()
Else
MsgBox("Your Username or Password is invalid", MsgBoxStyle.Critical)
Me.txtUsername.Text = ""
Me.txtPassword.Text = ""
Me.txtUsername.Focus()
strsql.Connection.Close()
strsql2.Connection.Close()
End If
The error here is the strsql2.connection.open() <--- it says that the connection is not close. still open.
I edited your question because you tagged it VBA and this is VB.NET
You have several problems with your code.
You should add Error trapping with Try Catch and also your connection is not always closed
To only fix the actual issue, test if the connection is open before trying to open it
If strsql2.Connection.State = ConnectionState.Open Then
Console.WriteLine("COnnection already open, closing it")
strsql2.Connection.Close()
End If
strsql2.Connection.Open()

login in vb.net and sql server 2008

How I'm going to redirect to another page after login is successful ?
and how I'm going to check if the username & password are correct or not ?
this is my code for login :
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
If txtUser.Text = "" Then
MsgBox("Please Enter The Username !", MsgBoxStyle.OkOnly)
ElseIf txtPass.Text = "" Then
MsgBox("Please Enter The Password !", MsgBoxStyle.OkOnly)
End If
Dim connectionString As String = "server=''; user id=''; password=''; Database=''"
Dim conLogin As SqlClient.SqlConnection = New SqlClient.SqlConnection(connectionString)
Dim queryString As String = "SELECT login VALUES " _
& "(#username, #password) "
You need to learn SQL first: The following statement is not correct SQL.
SELECT login VALUES (#username, #password)
The statement should look like this:
SELECT * FROM Login WHERE UserName = #username AND Password = #password
Then you need to set the command parameters #username and #password.
I also doubt that the connection string you're using is correct. Use an SqlConnectionStringBuilder to create a correct connection string. In addition, you do not open the connection, so there's not database access possible.
To redirect to another page, see code below
response.redirect("abc.apsx")
You can also use datareader and this sql query
Select count(*) from Login where UserName = #username and Password = #password
if (dr > 0) {
response.redirect('home');
}
else{
//error message
}
just search about datareader.......
...Hope it helps...
Here is the complete code for Login Function.
For more details visit my blog : http://uncopyrightables2011.blogspot.com/
or Tweet me : #MaxRohana
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Passowrd As String
Dim Passowrd2 As String
Dim userName As String
Try
If
'change the data source and initial catalog according to your sql server engine and data base
con.ConnectionString = "Data Source = YOUR-PC; Initial Catalog = YOUR-DB; Integrated Security = True"
con.Open()
cmd.Connection = con
'change the data fields names and table according to your database
cmd.CommandText = " SELECT UserName, Password FROM AdminDetail WHERE (UserName = '" & txtUsername.Text & "' ) AND (Password = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
'Do something here
Passowrd = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Passowrd2 = txtPassword.Text()
If Passowrd = Passowrd2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
frmMain.Show()
Me.Hide()
'Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
'Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
End Sub