i need some help in VB. I just started learning vb today.
so I have an MDIParent form, which contain login, logout(disabled) and other disabled strip menu.
so when i click the login, the login form is appeared as MDI child window.
the question is, when i successfully logged in i want to make the login Strip Menu disabled, enabling the logout Strip Menu and the other strip menu. I have tried to make it. Here's my code now :
Imports MySql.Data.MySqlClient
Public Class LoginForm
Dim mdiP As New MDIParent
Dim myconn As New MySqlConnection("Server=localhost; User Id=root; Password=; Database=apotek_db")
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If UsernameTextBox.Text = "" Or PasswordTextBox.Text = "" Then
MsgBox("Please insert username and password")
End If
Dim username As String = UsernameTextBox.Text
Dim password As String = PasswordTextBox.Text
Dim myAdapter As New MySqlDataAdapter("select * from admin where USERNAME = '" & username & "' and PASSWORD = '" & password & "'", myconn)
Dim myDataTable As New DataTable
myAdapter.Fill(myDataTable)
If myDataTable.Rows.Count < 1 Then
PasswordTextBox.Clear()
UsernameTextBox.Clear()
MsgBox("Invalid username or password")
Else
MsgBox(username & " Successfully logged in")
mdiP.logOutMenu.Enabled = True
mdiP.logInMenu.Enabled = False
mdiP.TransaksiPenjualanToolStripMenuItem.Enabled = True
mdiP.DataObatToolStripMenuItem.Enabled = True
Me.Close()
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
mdiP.Show()
Me.Close()
End Sub
End Class
But the code above doesn't disabling or enabling anything in the MDI parent. it just showing message box than i successfully logged in, and close the login form. thats it.
so anyone have any solution for me?
Thanks in advance,
Rezz.
Related
I'm pretty sure this code used to allow me to login using the SQL statement below, but now it doesn't and just clears the text boxes.
There is also an error message that I would like displayed when the username and password do not match that in the database. This is, like the other one, a label that the visibility would need changing. I had this code:
Try
UserType = GetUserType(txtUsername.Text.Trim, txtPass.Text.Trim)
Catch ex As Exception
lblErrorMatch.Visible = True
End Try
However, this just clears the text boxes when the details do not match.
Imports System.Data.OleDb
Public Class frmLogin
Private DBCmd As New OleDbCommand
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;"
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
Dim UserType As Object
'Distinguishing beetween different users
If UserType Is Nothing Then
lblErrorEmpty.Visible = True
ElseIf UserType.ToString = "MANAGER" Then
frmHomeManager.Show()
ElseIf UserType.ToString = "RECEPTIONIST" Then
frmHomeReceptionist.Show()
End If
'Username and password not matching error message
'Empty textboxes error message
If txtUsername.Text = "" OrElse txtPass.Text = "" Then lblErrorEmpty.Visible = True : Exit Sub
txtUsername.Clear()
txtPass.Clear()
chkShowPass.Checked = False
End Sub
Private Function GetUserType(Username As String, Pass As String) As Object
Dim UserType As Object
'Pull username and password from the database to check against the entered login details
Using DBCon As New OleDb.OleDbConnection(ConStr),
DBCmd As New OleDbCommand("SELECT UserType FROM tblEmployeeLogin WHERE [Username] = #Username AND [Pass] = #Pass", DBCon)
DBCmd.Parameters.Add("#Username", OleDbType.VarChar).Value = Username
DBCmd.Parameters.Add("#Pass", OleDbType.VarChar).Value = Pass
DBCon.Open()
UserType = DBCmd.ExecuteScalar.ToString
End Using
Return UserType
End Function
Private Sub chkShowPass_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowPass.CheckedChanged
'Show password when checkbox is checked
If chkShowPass.Checked = True Then
txtPass.PasswordChar = Nothing
ElseIf chkShowPass.Checked = False Then
txtPass.PasswordChar = "*"
End If
End Sub
Private Sub txtUsername_TextChanged(sender As Object, e As EventArgs) Handles txtUsername.TextChanged, txtPass.TextChanged
'Make error message disappear after text is enetered into either of the text boxes
lblErrorEmpty.Visible = False
lblErrorMatch.Visible = False
End Sub
Private Sub lnkClear_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lnkClear.LinkClicked
txtUsername.Clear()
txtPass.Clear()
chkShowPass.Checked = False
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
'Close the form down which stops the application
Me.Close()
End Sub
End Class
Thank you for your time :)
I recently made a login like what you're trying to do. Hopefully you understand this code and it helps:
Dim CMD As OleDbCommand = New OleDbCommand("SELECT * FROM Staff WHERE Login = '" & ID & "'", Con)
Dim user As String
Try
Con.Open()
Dim sdr As OleDbDataReader = CMD.ExecuteReader()
If (sdr.Read() = True) Then
user = sdr("Login")
MessageBox.Show("Login Successful!")
ActiveUser.IsLoggedIn = True
Else
MessageBox.Show("Invalid username or password!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
Con.Close()
End Try
I am trying to set-up a login page that checks the user's credentials from an MS Access database. When I run the code, it says that the fill method needs one or more parameters. Here's the code I'm using:
Public Class login
Public Shared dslogin As New DataSet
Public Shared con As New OleDb.OleDbConnection
Dim da1 As New OleDb.OleDbDataAdapter
'Global variables
Public Shared currentloginID As Integer = 0
Public Shared tbusername As TextBox
Public Shared tbpassword As TextBox
Private Function OpenDBConnection1()
Dim directory1 As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Return "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = " & directory1 & "\IEshiDBv1.accdb"
End Function
'login button
Private Sub btnLOGIN_Click(sender As Object, e As EventArgs) Handles btnLOGIN.Click
Dim username As String = txtusername.Text
Dim password As String = txtpassword.Text
If username = "" Or password = "" Then
MsgBox("Please enter log-in details")
con.Close()
Exit Sub
Else
Dim sqllogin As String = ("SELECT * FROM LoginRcrds WHERE LoginUserName = " & username)
da1 = New OleDb.OleDbDataAdapter(sqllogin, con)
da1.Fill(dslogin, "LoginCredentials")
con.Close()
Dim dtlogin As DataTable = dslogin.Tables("LoginCredentials")
Dim rowlogin As DataRow
For Each rowlogin In dtlogin.Rows
If password = rowlogin("LoginPW") Then
homepage.Show()
Me.Hide()
Exit For
End If
Next
MsgBox("Incorrect log-in credentials. Please try again")
Exit Sub
End If
End Sub
'Onload subroutine
Private Sub login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = (OpenDBConnection1())
con.Open()
End Sub
End Class
The error occurs at
da1.Fill(dslogin, "LoginCredentials")
and the error message says " No value given for one or more required parameters."
I read somewhere that .Fill requires three parameters: (DataSet, RecordSet, TableName). I never tried this because I don't understand what RecordSet means.
Edit: I've checked another program with a 4.0 Oledb provider and changed it to 12.0. The same error appeared. It seems that the Fill method of the DataAdapter of Oledb 12.0 requires more than 2 parameters. Can somebody explain this?
I have a vb.net application that is a main MDI parent form with several child forms. In one of the child forms I have a place to insert data to create user accounts and store them in a database I created in visual studio called "UserAccounts" with a data table called "dtUsers". There is also a login form that has a place for a username and password and I want the program to search the datatable to make sure the username exists and that the password is correct. This is the code for the login form I am using the string "admin" as a placeholder for a "username" and the string password as a placeholder for a password.
Private Sub LoginButton_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
If UserNameTextBox.Text = "admin" And UserPasswordTextBox.Text = "password" Then
My.Forms.EOM_Parent.MenuStrip1.Enabled = True
My.Forms.EOM_Parent.TreeView1.Enabled = True
My.Forms.EOM_Parent.ToolStrip1.Enabled = True
Close()
Else
MsgBox("You have entered the wrong username/password combination.")
End If
End Sub
This is the code from my add user form.
Public Class AddUserForm
Private myXmlFilePath = "xmlUserData.xml"
Private Sub AddUserForm_Load(sender As Object, e As EventArgs) Handles Me.Load
If My.Computer.FileSystem.FileExists(myXmlFilePath) = True Then
UserAccounts.ReadXml(myXmlFilePath)
End If
End Sub
Private Sub CancelUserButton_Click(sender As Object, e As EventArgs) Handles CancelUserButton.Click
Close()
End Sub
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
Me.Validate()
DtUsersBindingSource.EndEdit()
UserAccounts.WriteXml(myXmlFilePath)
End Sub
End Class
The fields in the data table are:
UserID
FirstName
LastName
AdminUser
Password
and the UserID is the key. And the xml file is xmlUserData.xml
The only solutions I can find online are for SQL. And I know this isn't a secure way to store usernames and passwords.
Declare the DataTable as Friend in a Module:
Module GlobalStuff
Friend dt As New DataTable("Foo")
End Module
And to reference in your login form...
With dt.Select("AdminUser = '" & UserNameTextBox.Text & "' And Password = '" & UserPasswordTextBox.Text & "'")
If .Count = 1 Then
' Good Login
End If
End With
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.
I'm new to VB.net. So here is what I want to do which I am having some serious problem
Using the "Get_Computer_Name form" will post the username and account type into another form. The Get_Computer_Name also gets the computer name where it will be sent to a module and that module will work as the main connection. Now I have tried to separate the login form and form that gets the computer name but that didn't work (I also want to try that method).
The problem with my current method is that it can only perform one thing at a time. It fails to post the username and account type and it fails to send the computer name to the module. Now strangely there is a way around. If I comment out the post username and account type, the computer name will be sent to the module and the module will work and connect to the database. Now if I choose not to comment out the code that post the username and account to the other form, the computer name won't be sent to the module that handles the connection thus failing to connect to the database.
I am open to other suggestions rather than doing it this way.
Thank you
'Here is my code for "Get_Computer_Name form"
Imports System.Data.SqlClient
Public Class Get_Computer_Name
Public Sub Get_Computer_Name_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cmbcomputername.Text = My.Computer.Name
connect()
End Sub
Private Sub cmbcomputername_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbcomputername.SelectedIndexChanged, cmbcomputername.TextChanged
cmbcomputername.Text = My.Computer.Name
End Sub
Public Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
datasource = cmbcomputername.Text
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim reader As SqlDataReader
Dim sqlstatement As SqlCommand = New SqlCommand
sqlstatement.Connection = connection
Try
sqlstatement.CommandText = "Select account_username, account_password, account_type " &
"from account_login where account_username='" & txtusername.Text & "' and account_password='" & txtpassword.Text & "'"
reader = sqlstatement.ExecuteReader()
If (reader.Read()) Then
Dim application_form As application_form
application_form = New application_form
application_form.Show()
application_form = Nothing
Me.Visible = False
'This is the code that post the username and account type to the other form (application form). If I comment this code out, the system successfully connects to the database
application_form.lblusername.Text = (reader("account_username").ToString)
application_form.lblaccount_type.Text = (reader("account_type").ToString)
sqlstatement.Dispose()
reader.Close()
connection.Close()
Else
connection.Close()
MsgBox("Invalid")
End If
reader.Close()
Catch ex As Exception
End Try
End Sub
End Class
'This is the code for the module that holds the main connection string
Public connection As SqlConnection = New SqlConnection
Public datasource As String
Public database As String = "bpmi"
Public sqlmainconnector As String
Public Sub connect()
sqlmainconnector = "Data Source=" & datasource & ";Initial Catalog=bpmi;Integrated Security=True"
connection.ConnectionString = sqlmainconnector
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
Else
connection.Close()
End If
Catch ex As Exception
End Try
End Sub
'And this code is the form where the username and account type will be posted
Imports System.Data.SqlClient
Public Class application_form
Dim sqlcommand As SqlCommand
Dim da As SqlDataAdapter
Dim table As New DataTable
Dim dategrabberapp As String
Dim dategrabberben As String
Dim benidgrabber As String
Private Sub Form1_Load(sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
connect()
filldatagrid(updateappdatagrid, updatebendatagrid)
fillcomboboxstatus(cmbstatus)
fillcomboboxposition(cmbappworkposition)
fillcomboboxrelationship(cmbrelation)
fillcomboboxrelationshipupdate(cmbrelationbenupdate)
fillcomboboxstatusupdate(cmbappstatusupdate)
fillcomboboxpositionupdate(cmbappworkposupdate)
'this is where the account type will got to
If lblaccount_type.Text <> "Administrator" Then
Me.TabControl1.TabPages(1).Enabled = False
Me.TabControl1.TabPages(2).Enabled = False
MsgBox("As a 'Staff', you are not permitted to do any updates")
updateappdatagrid.Hide()
updatebendatagrid.Hide()
End If
End Sub
End Class