a beginner in vb.net.. working on a login form - vb.net

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you

Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
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
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.

Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

Related

Database query not returning results from value

I am making a work management system and I am fairly new to Visual Basic.
What I am trying to do is retrieve the name of the employee from the database with the given ID. After that I want this name to be displayed in a Label. After that, he can press the Work Start or Work end buttons.
Here is the code:
Private Function employeeSearchwithID(PersonalNr As String) As String
Dim mitarbeiter As String
Dim r As DataRow
Access.ExecQuery("SELECT [Vorname], [Name] from [TA-Personal] WHERE ([Personal_Nr] = '" & PersonalNr & "');")
'Report and Abort on Erros or no Records found
If NoErros(True) = False Or Access.RecordCount < 1 Then Exit Function
r = Access.DBDT.Rows(0)
'Populate Label with Data
mitarbeiter = r.Item("Vorname") & " " & r.Item("Name")
Return mitarbeiter
End Function
It is used like this:
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Label5.Text = employeeSearchwithID(tbxUserInput.ToString)
End If
End Sub
So, the plan is to have this program running on a tablet connected to a scanner. Every employee will have a personal card. When they scan the card, I want their names to be displayed. Of course, the card will be with the ID. But I am having trouble with the names: when I give my personal number it comes up as an empty string.
I have a separate DB Module. I learned from a tutorial:
Imports System.Data.OleDb
Public Class DBControl
' DB Connection
Public DBCon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\recycle2000.mdb;")
'DB Command
Public DBCmd As OleDbCommand
'DB Data
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'Public Myreader As OleDbDataReader = DBCmd.ExecuteReader
'Query Paramaters
Public Params As New List(Of OleDbParameter)
' Query Stats
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'Reset Query Stats
RecordCount = 0
Exception = ""
Try
'Open a connection
DBCon.Open()
'Create DB Command
DBCmd = New OleDbCommand(Query, DBCon)
' Load params into DB Command
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
' Clear params list
Params.Clear()
' Execute command & fill Datatable
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
' Close your connection
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
' Include query & command params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
Without knowledge of the Access class, I have to recommend a different approach to querying the database. It is important to make sure that the database is not vulnerable to SQL injection, be it deliberate or accidental. The way to do that is to use what are known as SQL parameters: instead of putting the value in the query string, the value is supplied separately.
Private Function EmployeeSearchwithID(personalNr As String) As String
Dim mitarbeiter As String = String.Empty
Dim sql = "SELECT [Vorname], [Name] from [TA-Personal] WHERE [Personal_Nr] = ?;"
Using conn As New OleDbConnection("your connection string"),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#PersonalNr",
.OleDbType = OleDbType.VarChar,
.Size = 12,
.Value = personalNr})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.Read() Then
mitarbeiter = rdr.GetString(0) & " " & rdr.GetString(1)
End If
End Using
Return mitarbeiter
End Function
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Dim employeeName = EmployeeSearchwithID(tbxUserInput.Text.Trim())
If String.IsNullOrEmpty(employeeName) Then
MessageBox.Show("Not found.", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Label5.Text = employeeName
End If
End If
End Sub
The Using command makes sure that the "unmanaged resources" involved in querying a database are cleaned up afterwards, even if something goes wrong.
You will need to change the value of OleDbType.VarChar and .Size = 12 to match the type and size of that column in the database.
The name of the parameter is only for convenience with OleDb because it is ignored in the actual query, which uses "?" as a placeholder. Please see OleDbCommand.Parameters Property for full information.
If it still does not work, then please enter the ID manually in the tbxUserInput and see if you can make it work that way.
Hang on... tbxUserInput.ToString should be tbxUserInput.Text. But everything else I wrote still applies.

vb.net // Failed to connect to the database ? Login System Check the user if admin or not

Hello guys, I am implementing a login system where there are two users it's either the admin or the superadmin, however it always fail to connect to the database. I'm kinda new to VB.net and I'm trying to figure out on how this make thing work and yep I searched up the web on how to create on but it fails, and btw here's the error log generated after logging in
Failed to Connect to the Database
A first chance exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Imports System.Data.OleDb
Imports System.Data
Public Class LoginFrm
Private Sub LoginBtn_Click_1(sender As Object, e As EventArgs) Handles LoginBtn.Click
If userBox.Text = "" Or passwordBox.Text = "" Then
MessageBox.Show("Username and password are blank", "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|\ResortReservationSystem.accdb"
Dim sql As String = "SELECT * FROM userTable WHERE userName='" & userBox.Text & "' AND passWord = '" & passwordBox.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
sqlCom.Connection = conn
sqlCom.Connection.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Item("userType") = "SuperAdmin" Then
welcomeFrm.Show()
Me.Hide()
End If
If sqlRead.Item("userType") = "Admin" Then
manageEmployeeForm.Show()
Else
MessageBox.Show("Username and Password do not match.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
userBox.Text = ""
passwordBox.Text = ""
userBox.Focus()
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
Edit: I have fixed some issues and now I am encountering this,
No data exists for the row/column. For what I know, .Item is to get the fetch the data, but it seems like it doesnt work for me.
table name: userTable
fields: userName, passWord, userType
datas: John, Doe, SuperAdmin
The point of a data reader is to read data. If you have done any reading on data readers and their use then you know that you have to call the Read method to actually read a record. You aren't calling Read, hence there's no data in your data reader.
If userBox.Text = "" Or passwordBox.Text = "" Then
Change the Or to OrElse to short circuit the If.
Connections and commands need to be closed and disposed. A Using...End Using block will do this for you even if there is an error.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the command text and connection directly to the constructor of the command.
Never concatenate strings with user input to build sql statements. You risk sql injection which can ruin your database. It also makes the sql statement easier to write because you don't have to use all those single and double quote and ampersands.
You are only using a single piece of data so don't return all the fields. You only need userType.
Always use parameters. Access (OleDb) does not care about the name of the parameter. I just use appropriate names for readability. What is important is the order that the parameter appears in the sql statement must match the order that the parameter is added to the parameters collection. I had to guess at the datatype and field size of the parameters. Check your database for the real values and correct the code accordingly.
Since we are only getting a single piece of data, we can use .ExecuteScalar which returns the first column of the first row of the result set.
The End Using closes and disposes the connection and command so now we can mess with returned data.
Sidenote: Your problem was that a reader does not start reading the returned rows until you call reader.Read. This is no longer relevant since we are not using a reader.
Private Sub LoginBtn_Click_1(sender As Object, e As EventArgs) Handles LoginBtn.Click
Dim AdminType As String
If userBox.Text = "" OrElse passwordBox.Text = "" Then
MessageBox.Show("Username and password must be filled in.", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Using conn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ResortReservationSystem.accdb"),
sqlCom As New OleDbCommand("SELECT userType FROM userTable WHERE userName= #User AND passWord = #Password", conn)
With sqlCom.Parameters
.Add("#User", OleDbType.VarChar, 100).Value = userBox.Text
.Add("#Password", OleDbType.VarChar, 100).Value = passwordBox.Text
End With
conn.Open()
AdminType = sqlCom.ExecuteScalar.ToString
End Using
If String.IsNullOrEmpty(AdminType) Then
MessageBox.Show("Username and Password do not match.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
userBox.Text = ""
passwordBox.Text = ""
userBox.Focus()
ElseIf AdminType = "SuperAdmin" Then
welcomeFrm.Show()
Me.Hide()
ElseIf AdminType = "Admin" Then
manageEmployeeForm.Show()
End If
End If
End Sub

how to display data in text box in vb.net using sql

Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" Or txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
sql = "Select * From `maintenance` fine ='" & txtfine.Text & "' "
reloadtxt(sql)
End sub
how will i display the fine in txtfine.text from my maintenance database after it satisfy the condition from txtremarks. i tried some youtube tutorials but only displaying it from data grid .. want i basically want is directly display it from database to textbox. btw im newbie in vb programming thank you in advance
for my reloadtxt this is the code.
Public Sub reloadtxt(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
dt = New DataTable
da = New MySqlDataAdapter(sql, con)
da.Fill(dt)
Catch ex As Exception
' MsgBox(ex.Message & "reloadtxt")
Finally
con.Close()
da.Dispose()
End Try
End Sub
To populate an object with data from a database you need to access the objects text property.
Textbox1.Text = "Some Text, static or dynamic"
Since you are pulling the data from a datatable you would access the column named "fine" and put that value in the textbox.text property.
Textbox1.Text = dt.row(0).item("fine").tostring
Changed Or to OrElse because it short circuits the If and doesn't have to check the second condition if the first condition is True.
In the reloadtxt method you filled a DataTable and did nothing with it. I changed it to a Function that returns the DataTable. The connection and command are now included in a Using...End Using block so they are closed and disposed even if there is an error.
Never concatenate strings to build an sql statement. Always used parameters.
Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" OrElse txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
Dim dt = reloadtxt()
DataGridView1.DataSource = dt
End If
End Sub
Public Function reloadtxt() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("Select * From maintenance Where fine = #Fine", con)
cmd.Parameters.Add(#Fine, MySqlDbType.VarChar, 50).Value = txtfine.Text
Try
con.Open()
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MsgBox(ex.Message & "reloadtxt")
End Try
End Using
Return dt
End Function

simple login form error VB 2010

I've search a lot of resources and couldn't fix it.
My problem is when I click the button event the next form doesn't show and also I want to close my login form at the same time.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim firstname As String = ""
Dim lastname As String = ""
Dim ara As Boolean = False
cn = New OleDbConnection(con)
cn.Open()
Dim user As String
Dim pass As String
user = TextBox1.Text
pass = TextBox2.Text
With cmd
.Connection = cn
.CommandText = "Select * from users WHERE username='" & user & "' AND password='" & pass & "'"
.ExecuteNonQuery()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
ara = True
While rdr.Read()
firstname = rdr("firstname").ToString
lastname = rdr("lastname").ToString
lib_name = firstname + lastname
End While
If ara = True Then
Form2.Show()
Me.Close()
x = True
Else
MsgBox(" Access Denied!" + Environment.NewLine + "Sorry, username or password is incorrect!")
End If
End If
End With
cn.Close()
cmd.Dispose()
1 : You are opening the gates of SQL INJECTION. Read more . Instead of passing values directly in your query, pass parameters first and use them later(For unknown reason, the code formatting is not working below) :
Dim cmd as New OleDbCommand("Select * from users WHERE username=#user AND password=#pass" , con)
With cmd
.Parameters.Add("#user", OleDbType.Varchar).Value = user
.Parameters.Add("#user", OleDbType.Varchar).Value = password
End With
2 : Your If statement will only work IDateReader.HasRows returns true and if ara=True which is unnecessary. .HasRows is a boolean, you don't need to create another boolean and pass the value to it. However, the rest of your code will only execute if your conditions match
3 : Form1.Close and AnotherForm.Show will never work if in your Project Proerties , Shutdown Mode is set to On main window close(by default). Either change it to On Explicit window close or On last window close or change
Me.CLose To
Me.Hide
4 : In order to reduce too much code , you can use Using Statement :
Using cmd as New SqlCommand("Select * from users WHERE username=#user AND password=#pass" , con)
'''codes here
End Using
''Now no need to call cmd.Dispose
Hope this helps :)

Attempting to validate username (email address) and password - having issues - vb.net

I have a Windows Form app that is not properly validating the user input information. Need some help.
I inserted the Microsoft Login form and am writing code to verify the user credentials. Using an Access DB to store and retrieve info. Two tables - one for email address and another for password.
I verify format of the email addy using regex. This works very well.
I validate the email address is in correct form and verify it is in the table (this works well). Then I attempt to read the password (appears this is not working as expected) and then read both bits of information from the tables. Next, I test to make sure both are present. If both are present control is passed to another form.
My issue is reading/verifying the password.
Here is my Visual Studio VB.net code.
Private Sub OK_Click(sender As System.Object, e As System.EventArgs) Handles OK.Click
Try
If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
If (match.Success) Then
Try
If i = 0 Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
'Change the following to your access database location
dataFile = "\11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
i = 1
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
'the query:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "'", myConnection)
Dim com As OleDbCommand = New OleDbCommand("SELECT * FROM [Password] WHERE [Password] = '" & txtPassword.Text & "'", myConnection2)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
Dim drp As OleDbDataReader = com.ExecuteReader()
' the following variable is hold true if EmailAddress is found, and false if EmailAddress is not found
Dim userFound As Boolean = False
' the following variable is hold true if Password is found, and false if Password is not found
Dim passwordFound As Boolean = False
' the following variables will hold the EmailAddress and Password if found.
Dim EmailAddressText As String = ""
Dim PasswordText As String = ""
'if found:
While dr.Read()
userFound = True
EmailAddressText = dr("EmailAddress").ToString
End While
While drp.Read()
passwordFound = True
PasswordText = drp("Password").ToString
End While
'checking the result
If userFound = True And passwordFound = True Then
frmMain.Show()
frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
Else
MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
End Sub
Well first your approach isn't really safe due to the fact the the password isn't encrypted and that either there is no link between email and password ideally you would have table for example:
USER
--UID
--Email
PASS
--ID
--UID
--PASS
And you would hash your password for example sha512 furthermore for more security you would use Salt and certificates to secure the database connection.
Then you could do:
Hash current password in textbox and execute:
"SELECT USER.Email FROM USER,PASS WHERE USER.Email='TEXTBOX_EMAIL' AND USER.UID = PASS.UID"
Check if you have result if yes your connected.
However I tried to correct a bit what you did in the above code. Having used only SQLClient and not Olecommand i tried to keep what you did so there might be few syntax errors but should be ok:
Try
If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
If (match.Success) Then
Dim passwordFound As Boolean
Dim userFound As Boolean
Using con As New SqlClient.SqlConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =\ 11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb")
'Using to make sure connection is disposed
'Open connection
con.Open()
'Prepare sql
Dim command As New OleDbCommand("SELECT [emailAddress] FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "';", con)
'Create the reader
Dim reader As OleDbDataReader = command.ExecuteReader()
Dim Id As String = ""
' Call Read before accessing data.
While reader.Read()
'Get data
Id = reader(0)
End While
'Close Reader
reader.Close()
If Id <> "" Then
'User found
userFound = True
'Prepare the second sql
Dim command2 As New OleDbCommand("SELECT [Password] FROM [Password] WHERE [Password] = '" & txtPassword.Text & "';", con)
'Prepare second reader
Dim reader2 As OleDbDataReader = command.ExecuteReader()
Dim Pass As String = ""
' Call Read before accessing data.
While reader2.Read()
'Get tdata
Pass = reader2(0)
End While
reader.Close()
If Pass <> "" Then
'Pass found
passwordFound = True
Else
passwordFound = False
End If
Else
userFound = False
End If
'Close connection
con.Close()
'Clear connection pool
SqlConnection.ClearPool(con)
End Using
'checking the result
If userFound = True And passwordFound = True Then
frmMain.Show()
frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
Else
MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
Decided to combine the email and passwords into one table. Made everything easier for now. Thanks for your help and suggestions.