Imports System.Data.OleDb
Imports System.Data
Public Class frmLoginBP
Dim connection As New OleDbConnection(My.Settings.Business_ProfileConnectionString)
Private Sub lblInterfaceTypeTemp_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Format the timer.
lblDate.Text = Date.Now.ToString("dd-MM-yyyy hh:mm:ss")
End Sub
Private Sub lblDate_Click(sender As Object, e As EventArgs) Handles lblDate.Click
'Format the timer.
lblDate.Text = Date.Now.ToString("dd-MM-yyyy hh:mm:ss")
End Sub
Private Sub frmLoginBP_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Show initial panels when loading the program.
Timer1.Enabled = True
Dim connection As New OleDbConnection(My.Settings.Business_ProfileConnectionString)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'button Register
frmRegistrationBP.Show()
End Sub
Private Sub btnShowPassword(sender As Object, e As EventArgs) Handles PictureBox3.Click
If txtBPPassword.UseSystemPasswordChar = True Then
txtBPPassword.UseSystemPasswordChar = False
Else
txtBPPassword.UseSystemPasswordChar = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If txtBPID.Text = "" Or txtBPPassword.Text = "" Then
MsgBox("Enter Credentials", MsgBoxStyle.Exclamation, "Error!")
Else
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim cmd As New OleDbCommand("select count(*) from [Business Details] where Email=? and Password=?", connection)
cmd.Parameters.AddWithValue("#1", OleDbType.VarChar).Value = txtBPID.Text
cmd.Parameters.AddWithValue("#2", OleDbType.VarChar).Value = txtBPPassword.Text
Dim count = Convert.ToInt32(cmd.ExecuteScalar())
If (count > 0) Then
MsgBox("Login succeed!", MsgBoxStyle.Information)
frmWelcomeNew.Show()
Me.Hide()
Else
MsgBox("Account not found. Check your credentials!", MsgBoxStyle.Critical, "Error!")
End If
End If
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
txtBPID.Text = ""
txtBPPassword.Text = ""
End Sub
End Class
First, I need to create an account in order to login into my system, thus, I press "Register" button. After I fill up the required textboxes,
Imports System.Data.OleDb
Public Class frmRegistrationBP
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New OleDbConnection
Private Sub lblInterfaceTypeTemp_Click(sender As Object, e As EventArgs)
End Sub
Private Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
'Declare variable.
Dim opf As New OpenFileDialog
'Filter the file types.
opf.Filter = "Choose Image(*.jpg;*.png)|* .jpg;*.png"
If opf.ShowDialog = DialogResult.OK Then
'Assign the file to the picture box.
pcbBusinessPhoto.Image = Image.FromFile(opf.FileName)
End If
End Sub
Private Sub btnCancel_BizRegisPG1_Click(sender As Object, e As EventArgs) Handles btnCancel_BizRegisPG1.Click
Me.Close()
End Sub
Private Sub btnReset_BizRegisPG1_Click(sender As Object, e As EventArgs) Handles btnReset_BizRegisPG1.Click
txtBizAddress.Text = ""
txtBizAddress.Text = ""
txtBizName.Text = ""
txtBizPhoneNo.Text = ""
txtPassword.Text = ""
txtPasswordReenter.Text = ""
txtSSM.Text = ""
cboBizType.Text = ""
pcbBusinessPhoto.Image = Nothing
End Sub
Private Sub txtBizName_BizRegis_TextChanged(sender As Object, e As EventArgs) Handles txtBizName.TextChanged
End Sub
Private Sub btnNext_BizRegisPG1_Click(sender As Object, e As EventArgs) Handles btnNext_BizRegisPG1.Click
If txtSQAnswer.Text = "" OrElse cboSQ.Text = "" OrElse txtSSM.Text = "" OrElse txtBizAddress.Text = "" OrElse txtBizEmail.Text = "" OrElse txtBizName.Text = "" OrElse txtBizPhoneNo.Text = "" OrElse txtPassword.Text = "" OrElse txtPasswordReenter.Text = "" OrElse cboBizType.Text = "" Then
MsgBox("Please fill in the textboxes!", MsgBoxStyle.Critical, "Error!")
ElseIf txtPasswordReenter.Text <> txtPassword.Text Then
MsgBox("Your Reentered Password is not the same!", MsgBoxStyle.Critical, "Error!")
Else
If IsNumeric(txtBizPhoneNo.Text) = False Then
MsgBox("Enter numeric value only in Company Phone Number", MsgBoxStyle.Critical, "Error!")
ElseIf IsNothing(pcbBusinessPhoto.image) Then
MsgBox("Please upload Business Photo", MsgBoxStyle.Critical, "Error!")
Else
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\chiac\OneDrive\Desktop\OMC\Code\[OMC] Business Partner\[OMC] Business Partner\Business Profile.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into [Business Details] values (#SSM,#BizName,#Address,#Email,#HP,#BizType,#Password,#BusinessPhoto,#OHFrom,#OHTo,#SQ1,SQ1Answer)"
Dim cmd As OleDbCommand = New OleDbCommand(Command, myconnection)
cmd.Parameters.Add(New OleDbParameter("#SSM", CType(UCase(txtSSM.Text), String)))
cmd.Parameters.Add(New OleDbParameter("#BizName", CType(txtBizName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Address", CType(txtBizAddress.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Email", CType(txtBizEmail.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#HP", CType(txtBizPhoneNo.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#BizType", CType(cboBizType.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Password", CType(txtPassword.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#BusinessPhoto", pcbBusinessPhoto.Image))
cmd.Parameters.Add(New OleDbParameter("#OHFrom", CType(cboOHFrom.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#OHTo", CType(cboOHTo.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#SQ1", CType(cboSQ.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#DQ1Answer", CType(txtSQAnswer.Text, String)))
MsgBox("Record Saved")
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtSSM.Clear()
txtBizAddress.Clear()
txtBizEmail.Clear()
txtBizName.Clear()
txtBizPhoneNo.Clear()
txtPassword.Clear()
txtPasswordReenter.Clear()
cboBizType.Text = ""
cboOHFrom.Text = ""
cboOHTo.Text = ""
pcbBusinessPhoto.Image = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
frmRegistration2.Show()
Me.Hide()
End If
End If
End Sub
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
End Sub
Private Sub frmRegistrationBP_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
Imports System.Data.OleDb
Public Class frmRegistration2
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New OleDbConnection
Dim finalGender As String
Private Sub frmRegistration2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnUploadIC_Click(sender As Object, e As EventArgs) Handles btnUploadIC.Click
'Declare variable.
Dim opf As New OpenFileDialog
'Filter the file types.
opf.Filter = "Choose Image(*.jpg;*.png)|* .jpg;*.png"
If opf.ShowDialog = DialogResult.OK Then
'Assign the file to the picture box.
pcbIC.Image = Image.FromFile(opf.FileName)
End If
End Sub
Private Sub btnSubmit_BizRegisPG2_Click(sender As Object, e As EventArgs) Handles btnSubmit_BizRegisPG2.Click
If txtIC.Text = "" OrElse txtFirstName.Text = "" OrElse txtLastName.Text = "" OrElse txtEmail.Text = "" OrElse txtHP.Text = "" OrElse dtpDOB.Text = "" Then
MsgBox("Please fill in the textboxes!", MsgBoxStyle.Critical, "Error!")
Else
If IsNumeric(txtIC.Text) = False Then
MsgBox("Please insert numerical value in Identity Card Number!", MsgBoxStyle.Critical, "Error!")
ElseIf IsNothing(pcbIC.image) = True Then
MsgBox("Please insert Owner Photo!", MsgBoxStyle.Critical, "Error!")
ElseIf rbtFemale.Checked = False And rbtMale.Checked = False Then
MsgBox("Please select your gender!", MsgBoxStyle.Critical, "Error!")
ElseIf rbtAgree.Checked = False Then
MsgBox("Please AGREE with Goodstopia Terms & Conditions!", MsgBoxStyle.Critical, "Error!")
Else
If rbtMale.Checked = True Then
finalGender = "Male"
End If
If rbtFemale.Checked = True Then
finalGender = "Female"
End If
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\chiac\OneDrive\Desktop\OMC\Code\[OMC] Business Partner\[OMC] Business Partner\Business Profile.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into [Owner Details] values (#IC,#FirstName,#LastName,#Email,#HP,#DOB,#Gender,#ICPhoto)"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("#IC", CType(UCase(txtIC.Text), String)))
cmd.Parameters.Add(New OleDbParameter("#FirstName", CType(txtFirstName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#LastName", CType(txtLastName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Email", CType(txtEmail.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#HP", CType(txtHP.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#DOB", CType(dtpDOB.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Gender", finalGender))
cmd.Parameters.Add(New OleDbParameter("#ICPhoto", pcbIC.Image))
MsgBox("Record Saved")
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtIC.Clear()
txtFirstName.Clear()
txtLastName.Clear()
txtHP.Clear()
txtEmail.Clear()
rbtFemale.Checked = False
rbtMale.Checked = False
pcbIC.Image = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Me.Hide()
frmLoginBP.Show()
End If
End Sub
Private Sub rbtAgreeTerms_BizRegis_CheckedChanged(sender As Object, e As EventArgs) Handles rbtAgree.CheckedChanged
End Sub
End Class
I press 'Submit', my MS Access Login Database has captured all the data I typed.
After that, The login form will reappear again. However, even though I had saved the details in my Login DB. I still can't manage to Login into my system. My guess is that it's because the Database in the Login form has not 'refreshed' yet.
So my question is How do I 'refresh' the database in my login form?
Connections use unmanaged resources which they release in their Dispose method. You must Dispose connections. Using...End Using blocks handle this for us. Declare connections in the method where the are used, not at the Class level. Declare the connection string at the class level so it can be used in any method in the class.
Don't include empty Subs in your question. The Timer and the date label have nothing to do with the question. Don't include these methods.
Enable your Timer at design time. It is pointless to create a local variable for a new connection in Form.Load and then let it fall out of scope before it is ever used. Remember, connections need to be disposed.
In the btnShowPassword method (which is strangely a picture box, why?) you can toggle a Boolean property in a single line.
In Button1.Click use OrElse to short circuit the If. It will stop evaluating expressions as soon as it finds a True.
Now to the database code. You will never need to check ConnectionState because it will be declared in the method in a Using block. Both the connection and the command are included in the Using block because commands need to be disposed too. Don't open the connection until directly before the .Execute...
I am happy to see the use of Parameters. I used the actual parameter name in the CommandText. The question mark works fine but it easier to tie the parameters to the ParametersCollection when you can see names. Access only pays attention to the position but it makes it easier to read.
The vb specific CInt has been optimized in .net.
The first code block should look like this.
Private ConStr As String = My.Settings.Business_ProfileConnectionString '"Your connection string"
Private Sub btnShowPassword(sender As Object, e As EventArgs) Handles PictureBox3.Click
txtBPPassword.UseSystemPasswordChar = Not txtBPPassword.UseSystemPasswordChar
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If txtBPID.Text = "" OrElse txtBPPassword.Text = "" Then
MsgBox("Enter Credentials", MsgBoxStyle.Exclamation, "Error!")
Else
Dim count As Integer
Using connection As New OleDbConnection(ConStr),
cmd As New OleDbCommand("select count(*) from [Business Details] where Email=#1 and Password=#2", connection)
cmd.Parameters.AddWithValue("#1", OleDbType.VarChar).Value = txtBPID.Text
cmd.Parameters.AddWithValue("#2", OleDbType.VarChar).Value = txtBPPassword.Text
connection.Open()
count = CInt(cmd.ExecuteScalar())
End Using
If count = 0 Then
MsgBox("Login succeed!", MsgBoxStyle.Information)
frmWelcomeNew.Show()
Me.Hide()
Else
MsgBox("Account not found. Check your credentials!", MsgBoxStyle.Critical, "Error!")
End If
End If
End Sub
In the second Form I am dividing up the code in btnNext.Click method.
It would be rare for a phone number to have no dashes or maybe ext. but I left it alone. I just got rid of the IsNumeric left over from vb6.
I am surprised that you are not using the settings that you used in the first form. This might be your problem.
You do not need to convert a Text property to a String. It is already a String.
Private ConStr As String = My.Settings.Business_ProfileConnectionString '"Your connection string"
Private Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(*.jpg;*.png)|* .jpg;*.png"
If opf.ShowDialog = DialogResult.OK Then
pcbBusinessPhoto.Image = Image.FromFile(opf.FileName)
End If
End Sub
Private Sub btnNext_BizRegisPG1_Click(sender As Object, e As EventArgs) Handles btnNext_BizRegisPG1.Click
If Not ValidateInput() Then
Exit Sub
End If
Try
InsertData()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return
End Try
MsgBox("Record Saved")
ClearForm()
frmRegistration2.Show()
Me.Hide()
End Sub
Private Function ValidateInput() As Boolean
If txtSQAnswer.Text = "" OrElse cboSQ.Text = "" OrElse txtSSM.Text = "" OrElse txtBizAddress.Text = "" OrElse txtBizEmail.Text = "" OrElse txtBizName.Text = "" OrElse txtBizPhoneNo.Text = "" OrElse txtPassword.Text = "" OrElse txtPasswordReenter.Text = "" OrElse cboBizType.Text = "" Then
MsgBox("Please fill in the textboxes!", MsgBoxStyle.Critical, "Error!")
Return False
End If
If txtPasswordReenter.Text <> txtPassword.Text Then
MsgBox("Your Reentered Password is not the same!", MsgBoxStyle.Critical, "Error!")
Return False
End If
Dim Phone As Long
If Not Long.TryParse(txtBizPhoneNo.Text, Phone) Then
MsgBox("Enter numeric value only in Company Phone Number", MsgBoxStyle.Critical, "Error!")
Return False
End If
If IsNothing(pcbBusinessPhoto.image) Then
MsgBox("Please upload Business Photo", MsgBoxStyle.Critical, "Error!")
Return False
End If
Return True
End Function
Private Sub InsertData()
Using myconnection As New OleDbConnection(ConStr),
cmd As New OleDbCommand("insert into [Business Details] values (#SSM,#BizName,#Address,#Email,#HP,#BizType,#Password,#BusinessPhoto,#OHFrom,#OHTo,#SQ1,SQ1Answer)", myconnection)
cmd.Parameters.Add("#SSM", OleDbType.VarChar).Value = txtSSM.Text.ToUpper
cmd.Parameters.Add("#BizName", OleDbType.VarChar).Value = txtBizName.Text
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = txtBizAddress.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = txtBizEmail.Text
cmd.Parameters.Add("#HP", OleDbType.VarChar).Value = txtBizPhoneNo.Text
cmd.Parameters.Add("#BizType", OleDbType.VarChar).Value = cboBizType.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = txtPassword.Text
cmd.Parameters.Add("#BusinessPhoto", OleDbType.LongVarBinary).Value = pcbBusinessPhoto.Image))
cmd.Parameters.Add("#OHFrom", OleDbType.VarChar).Value = cboOHFrom.Text
cmd.Parameters.Add("#OHTo", OleDbType.VarChar).Value = cboOHTo.Text)
cmd.Parameters.Add("#SQ1", OleDbType.VarChar).Value = cboSQ.Text
cmd.Parameters.Add("#DQ1Answer", OleDbType.VarChar).Value = txtSQAnswer.Text
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Private Sub ClearForm()
txtSSM.Clear()
txtBizAddress.Clear()
txtBizEmail.Clear()
txtBizName.Clear()
txtBizPhoneNo.Clear()
txtPassword.Clear()
txtPasswordReenter.Clear()
cboBizType.Text = ""
cboOHFrom.Text = ""
cboOHTo.Text = ""
pcbBusinessPhoto.Image = Nothing
End Sub
And for the third Form
Private ConStr As String = My.Settings.Business_ProfileConnectionString '"Your connection string"
Private Sub btnSubmit_BizRegisPG2_Click(sender As Object, e As EventArgs) Handles btnSubmit_BizRegisPG2.Click
If Not ValidateInput() Then
Return
End If
Try
InsertOwner()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return
End Try
ClearForm()
MsgBox("Record Saved")
Me.Hide()
frmLoginBP.Show()
End Sub
Private Function ValidateInput() As Boolean
If txtIC.Text = "" OrElse txtFirstName.Text = "" OrElse txtLastName.Text = "" OrElse txtEmail.Text = "" OrElse txtHP.Text = "" OrElse dtpDOB.Text = "" Then
MsgBox("Please fill in the textboxes!", MsgBoxStyle.Critical, "Error!")
Return False
End If
Dim IC As Integer
If Not Integer.Parse(txtIC.Text, IC) Then
MsgBox("Please insert numerical value in Identity Card Number!", MsgBoxStyle.Critical, "Error!")
Return False
End If
If pcbIC.image Is Nothing Then
MsgBox("Please insert Owner Photo!", MsgBoxStyle.Critical, "Error!")
Return False
End If
If rbtFemale.Checked = False And rbtMale.Checked = False Then
MsgBox("Please select your gender!", MsgBoxStyle.Critical, "Error!")
Return False
End If
If rbtAgree.Checked = False Then
MsgBox("Please AGREE with Goodstopia Terms & Conditions!", MsgBoxStyle.Critical, "Error!")
Return False
End If
Return True
End Function
Private Sub InsertOwner()
Dim finalGender As String
If rbtMale.Checked = True Then
finalGender = "Male"
Else
finalGender = "Female"
End If
Dim Command = " insert into [Owner Details] values (#IC,#FirstName,#LastName,#Email,#HP,#DOB,#Gender,#ICPhoto)"
Using myconnection As New OleDbConnection(ConStr),
cmd As New OleDbCommand(Command, myconnection)
cmd.Parameters.Add("#IC", OleDbType.VarChar).Value = UCase(txtIC.Text)
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = txtFirstName.Text
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = txtEmail.Text
cmd.Parameters.Add("#HP", OleDbType.VarChar).Value = txtHP.Text
cmd.Parameters.Add("#DOB", OleDbType.VarChar).Value = dtpDOB.Text
cmd.Parameters.Add("#Gender", OleDbType.VarChar).Value = finalGender
cmd.Parameters.Add("#ICPhoto", OleDbType.LongVarBinary).Value = pcbIC.Image
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Private Sub ClearForm()
txtIC.Clear()
txtFirstName.Clear()
txtLastName.Clear()
txtHP.Clear()
txtEmail.Clear()
rbtFemale.Checked = False
rbtMale.Checked = False
pcbIC.Image = Nothing
End Sub
One more thing. Passwords should never be stored as plain text. Look up salting and hashing.
In your "register" method you explicitly put the connection string in code:
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\chiac\OneDrive\Desktop\OMC\Code\[OMC] Business Partner\[OMC] Business Partner\Business Profile.accdb"
In your login function you get it out of settings:
Dim connection As New OleDbConnection(My.Settings.Business_ProfileConnectionString)
(You also have the same code on the last line of Form Load, which is useless and should be removed)
--
I strongly suspect that these two connection strings point at different databases - your code is writing to a database, and you're opening it in access and seeing the data, but the app is looking in a different DB
If the settings mention |DataDirectory| or no absolute path, then the situation will potentially be even more confusing for you - you have a DB on your desktop, you have a DB in your project folder and you have a DB in your bin folder. If you ever make an update/insert that uses the connectionstring from settings, then you're editing the DB in the bin folder, but this DB is overwritten with a new copy of the DB from the project folder every time the app starts, so your changes are lost. Of course, in a production setting this doesn't happen because there is no bin folder or compilation process; it is merely a developer convenience (as a dev you're supposed to e.g. add new tables to the DB in the project folder)
Make sure your app is consistently looking in the same DB for all its operations (make your insert code use Settings too)
I am building this application within Vb 2008 that will allow users to login to their account (after having registered first) and view their information which has been stored in a database in MS Access. So far I have created the login and registration form, and the view profile form, but I want to know how on the users information from the data. I know that i will need to somehow send the id value of the user that has logged in from the login from to the view profile form,but how would I go about doing that.
Please if you could help I would really appreciate it
This is the code for my login form :
Imports System.Data.OleDb
Public Class Login
Dim ObjConnection As OleDbConnection
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim obj As New Profile
obj.StringPass = "SELECT ID FROM Members WHERE username='" & txtUsername.Text & "' "
' 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=" & Application.StartupPath & "\My_db.accdb"
'conn.Open()
'MsgBox("Susscess")
Dim sql As String = "SELECT * FROM Members WHERE username='" & txtUsername.Text & "' AND password = '" & txtPassword.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
Home.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()
End If
End If
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
'User clicking on cancel button only clears field
' and refocus to first field
txtUsername.Text = ""
txtPassword.Text = ""
txtUsername.Focus()
End Sub
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
Register.Show()
End Sub
End Class
This is code for my register for
Imports System.Data.OleDb
Public Class Register
Dim ObjConnection As OleDbConnection
Private Sub MembersBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MembersBindingNavigatorSaveItem.Click
Me.Validate()
Me.MembersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.My_dbDataSet)
End Sub
Private Sub Register_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ObjConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\My_db.accdb")
ObjConnection.Open()
End Sub
Private Sub btnRegsiter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRegsiter.Click
If txtForename.Text = "" Or txtSurname.Text = "" Or txtDate.Text = "" Or txtHeight.Text = "" Or txtWeight.Text = "" Or txtUsernameRegister.Text = "" Or txtPasswordRegister.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
If txtRe_type.Text = txtPasswordRegister.Text Then
Dim StrSQL As String = "INSERT INTO Members ([Forename], [Surname], [Date Of Birth], [Height], [Weigth], [Address] ,[Email], [Telephone No], [Username], [Password] ) VALUES (#ParForename, #ParSurname, #ParDate, #ParHeight, #ParWeigth, #ParAddress, #ParEmail, #ParTelephone, #ParUsername, #ParPassword)"
Dim ObjCommand As New OleDbCommand(StrSQL, ObjConnection)
ObjCommand.CommandType = CommandType.Text
ObjCommand.Parameters.Add("#ParForename", OleDbType.Char).Value = txtForename.Text
ObjCommand.Parameters.Add("#ParSurname", OleDbType.Char).Value = txtSurname.Text()
ObjCommand.Parameters.Add("#ParDate", OleDbType.Char).Value = txtDate.Text
ObjCommand.Parameters.Add("#ParHeight", OleDbType.Char).Value = txtHeight.Text
ObjCommand.Parameters.Add("#ParWeigth", OleDbType.Char).Value = txtWeight.Text
ObjCommand.Parameters.Add("#ParAddress", OleDbType.Char).Value = txtAddress.Text
ObjCommand.Parameters.Add("#ParEmail", OleDbType.Char).Value = txtEmail.Text
ObjCommand.Parameters.Add("#ParTelephone", OleDbType.Char).Value = txtTelephone.Text
ObjCommand.Parameters.Add("#ParUsername", OleDbType.Char).Value = txtUsernameRegister.Text
ObjCommand.Parameters.Add("#ParPassword", OleDbType.Char).Value = txtPasswordRegister.Text
ObjCommand.ExecuteNonQuery()
MsgBox("Registration Succesful")
Login.Show()
Me.Hide()
Else
MessageBox.Show("Your passwords do not match, please try again", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Login.Show()
Me.Hide()
End Sub
End Class
There are a lot of security concerns in your code that really should be addressed, but that notwithstanding, you just need to read the user id as part of the login procedure.
Currently you are just assuming validation on the fact that there is something to read, If sqlRead.Read() Then, rather than actually reading and storing a value (the user id) from the result set.
If you modify your SQL to, for example, SELECT user_id from .... and instead you made a call to sqlCom.ExecuteScalar() the return value would be the user_id which you could then store say in a session variable or some other persistent storage so that the id is available on the profile page.
Good-day,
I'm experiencing a very strange event that just started happening. Whenever I press the ENTER button on my keyboard, I expect the KeyDown event of my textbox to be raised and the corresponding code run. Instead, the form disappears (as if the .Hide() method has been called). When I debug, I see that the code that's supposed to run after the KeyDown event is raised is executing accordingly - but the form just disappears.
I've never encountered this before, so I don't know what to do. Any help would be appreciated. Thanks.
HERE'S THE CODE OF MY FORM:
Imports System.Net
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class FormAdd
#Region "VARIABLE DECLARATIONS CODE"
'FOR MySQL DATABASE USE
Public dbConn As MySqlConnection
'FOR CARD NUMBER FORMATTING
Private CF As New CardFormatter
'FOR CARD ENCRYPTION
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encryptedCard As String
#End Region
#Region "SUB-ROUTINES AND FUNCTIONS"
Private Sub GetDBdata()
Try
If TextBoxAccount.Text = "" Then
MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!")
TextBoxAccount.Focus()
Else
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Dim dbTable As New DataTable
dbAdapter.Fill(dbTable)
If dbTable.Rows.Count > 0 Then
'MessageBox.Show("Customer Account Found!")
Call recordFound()
TextBoxLastName.Text = dbTable.Rows(0).Item("nameLAST")
TextBoxFirstName.Text = dbTable.Rows(0).Item("nameFIRST")
TextBoxSalutation.Text = dbTable.Rows(0).Item("nameSALUTATION")
TextBoxCompanyName.Text = dbTable.Rows(0).Item("nameCOMPANY")
Else
'MessageBox.Show("No Customer Records Found! Please try again!")
Call recordNotFound()
ButtonReset.PerformClick()
End If
dbConn.Close()
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub SetDBData()
Try
dbConn = New MySqlConnection
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
Dim noCard As Boolean = True
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbQuery As String = "SELECT * FROM cc_master WHERE ccNumber = '" & TextBoxCard.Text & "';"
Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
dbCmd.CommandText = dbQuery
dbCmd.Connection = dbConn
dbAdapter.SelectCommand = dbCmd
dbData = dbCmd.ExecuteReader
While dbData.Read()
If dbData.HasRows() = True Then
MessageBox.Show("This Credit/Debit Card Already Exists! Try Another!")
noCard = False
Else
noCard = True
End If
End While
dbData.Close()
If noCard = True Then
'PERFORM CARD ENCRYPTION
'PERFORM DATABASE SUBMISSION
Dim dbQuery2 As String = "INSERT INTO cc_master (ccType, ccNumber, ccExpireMonth, ccExpireYear, ccZipcode, ccCode, ccAuthorizedUseStart, ccAuthorizedUseEnd, customer_accountNumber)" & _
"VALUES('" & ComboBoxCardType.SelectedItem & "','" & TextBoxCard.Text & "','" & TextBoxExpireMonth.Text & "','" & TextBoxExpireYear.Text & _
"','" & TextBoxZipCode.Text & "','" & TextBoxCVV2.Text & "','" & Format(DateTimePickerStartDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & Format(DateTimePickerEndDate.Value, "yyyy-MM-dd HH:MM:ss") & "','" & TextBoxAccount.Text & "');"
Dim dbData2 As MySqlDataReader
Dim dbAdapter2 As New MySqlDataAdapter
Dim dbCmd2 As New MySqlCommand
dbCmd2.CommandText = dbQuery2
dbCmd2.Connection = dbConn
dbAdapter2.SelectCommand = dbCmd2
dbData2 = dbCmd2.ExecuteReader
MessageBox.Show("Credit/Debit Card Information Saved SUCCESSFULLY!")
ButtonReset.PerformClick()
End If
dbConn.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Dispose()
End Sub
Private Sub ResetForm()
TextBoxAccount.Clear()
TextBoxLastName.Clear()
TextBoxFirstName.Clear()
TextBoxSalutation.Clear()
TextBoxCard.Clear()
ComboBoxCardType.SelectedItem = ""
TextBoxCompanyName.Clear()
TextBoxCVV2.Clear()
TextBoxExpireMonth.Clear()
TextBoxExpireYear.Clear()
TextBoxZipCode.Clear()
CheckBoxConfirm.Checked = False
TextBoxAccount.SelectionStart = 0
TextBoxAccount.SelectionLength = Len(TextBoxAccount.Text)
TextBoxAccount.Focus()
GroupBoxInputError.Hide()
LabelInstruction.Show()
GroupBox1.Height = 75
End Sub
Private Sub recordFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Green
LabelError.ForeColor = Color.White
LabelError.Text = "RECORD FOUND!"
GroupBoxInputError.Visible = True
GroupBox1.Height = 345
ButtonReset.Show()
LabelInstruction.Hide()
ComboBoxCardType.Focus()
End Sub
Private Sub recordNotFound()
GroupBoxInputError.Text = ""
LabelError.BackColor = Color.Red
LabelError.ForeColor = Color.White
LabelError.Text = "NO RECORD FOUND!"
GroupBoxInputError.Visible = True
End Sub
'Public Sub encryptCard()
' Try
' DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
' DES.Mode = System.Security.Cryptography.CipherMode.ECB
' Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateEncryptor
' Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBoxCard.Text)
' TextBoxCard.Text = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
' Catch ex As Exception
' MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
' End Try
'End Sub
#End Region
#Region "TOOLSTRIP MENU CONTROL CODE"
Private Sub ExitAltF4ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitAltF4ToolStripMenuItem.Click
End
End Sub
#End Region
#Region "BUTTON CONTROLS CODE"
Private Sub ButtonExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonExit.Click
FormMain.Show()
Me.Close()
End Sub
Private Sub ButtonReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonReset.Click
Call ResetForm()
End Sub
Private Sub ButtonSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSubmit.Click
Call SetDBData()
Call ResetForm()
End Sub
Private Sub ButtonEncrypt_Click(sender As System.Object, e As System.EventArgs) Handles ButtonEncrypt.Click
End Sub
#End Region
#Region "FORM CONTROLS CODE"
Private Sub FormAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
TextBoxAccount.Focus()
Me.KeyPreview = True
Timer1.Enabled = True
Timer1.Interval = 1
GroupBoxInputError.Hide()
ButtonSubmit.Hide()
ButtonReset.Hide()
GroupBox1.Height = 75
'LabelFooter.Text = "Welcome " & FormLogin.TextBoxUsername.Text() & " | Timestamp: " & Date.Now.ToString
Try
LabelIP.Text = "IP: " & Dns.GetHostEntry(Dns.GetHostName).AddressList(0).ToString
Catch ex As Exception
End Try
'Populate the Card Type combobox with the list of card types from the CardFormatter class
ComboBoxCardType.Items.AddRange(CF.GetCardNames.ToArray)
End Sub
#End Region
#Region "TEXTBOX CONTROLS CODE"
Private Sub TextBoxCard_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.GotFocus
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
Me.Refresh()
End Sub
Private Sub TextBoxCard_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxCard.LostFocus
'//CARD VALIDATION//
' This code will check whether the card is a valid number or not. It doesn't check to see if the card is active.
' The code calls on the creditcard function stored in MyModules.vb
Try
If creditcard(TextBoxCard.Text) Then
'MsgBox("Card is Valid")
TextBoxCard.BackColor = Color.GreenYellow
TextBoxCard.ForeColor = Color.Black
GroupBoxInputError.Visible = False
TextBoxCard.Text = CF.GetFormattedString(ComboBoxCardType.Text, TextBoxCard.Text)
Me.Refresh()
Else
BWErrorNotice.RunWorkerAsync()
'MsgBox("Invalid Card")
GroupBoxInputError.Visible = True
TextBoxCard.Focus()
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBoxAccount_GotFocus(sender As Object, e As System.EventArgs) Handles TextBoxAccount.GotFocus
TextBoxAccount.SelectAll()
End Sub
Private Sub TextBoxAccount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxAccount.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
If TextBoxAccount.Text <> "" Then
Call GetDBdata()
Else
MsgBox("You must enter an account number!", MsgBoxStyle.Exclamation, "ATTENTION PLEASE!")
TextBoxAccount.Focus()
End If
End If
'If e.KeyCode = Keys.Enter Then
' e.Handled = True
' SendKeys.Send("{Tab}")
'End If
End Sub
Private Sub TextBoxCard_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBoxCard.MouseClick
TextBoxCard.SelectionStart = 0
TextBoxCard.SelectionLength = Len(TextBoxCard.Text)
TextBoxCard.Text = TextBoxCard.Text.Replace("-", "")
Me.Refresh()
End Sub
#End Region
#Region "OTHER/MISCELLANEOUS CONTROLS CODE"
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LabelDateTime.Text = DateTime.Now
End Sub
Private Sub BWErrorNotice_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BWErrorNotice.DoWork
Do While Not creditcard(TextBoxCard.Text)
LabelError.BackColor = Color.Black
System.Threading.Thread.Sleep(500)
LabelError.BackColor = Color.Red
System.Threading.Thread.Sleep(500)
Loop
BWErrorNotice.CancelAsync()
End Sub
Private Sub CheckBoxConfirm_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxConfirm.CheckedChanged
If CheckBoxConfirm.Checked = True Then
ButtonSubmit.Show()
Else
ButtonSubmit.Hide()
End If
End Sub
#End Region
End Class
Although what follows will not likely solve the form disappearance problem, it will resolve a downstream issue:
In GetDBData(), you are assigning accountNumber to the value of TextBoxAcount.Text, which must be enclosed with quotes unless you employ a parameter which I strongly recommend you get in the habit of doing.
Dim dbAdapter As New MySqlDataAdapter("SELECT * FROM customer WHERE accountNumber = " & TextBoxAccount.Text, dbConn)
Parameters offer a number of benefits including implicit type conversions, injection attack prevention, and will sometimes even cure unexpected behaviors.
I figured out the problem. I was calling Dispose() at the end of my GetDBData() function - so the form was getting disposed before execution returned back to the TextBox. I deleted it and all is well again.