'System.InvalidOperationException' occurred in System.Data.dll - vb.net

I'm doing a simple login page for Visual Basic connected to an access database and I keep receiving this error when I run the project.
I would greatly appreciate it if anyone could help me resolve this.
Imports System.Data.OleDb
Public Class frmLogin
Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Login.accdb")
Dim objDA As New OleDb.OleDbDataAdapter("SELECT * FROM User", objConnection)
Dim objCB As New OleDb.OleDbCommandBuilder(objDA)
Dim objDS As New DataSet()
Public Username, Password As String
Dim UserFound As Boolean
Private Sub frmLogin_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Retrieve()
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Username = txtUser.Text
Password = txtPassword.Text
For i As Integer = 1 To (objDS.Tables("User").Rows.Count)
If CStr(objDS.Tables("User").Rows(i - 1).Item("Username")) =
Username And
CStr(objDS.Tables("User").Rows(i - 1).Item("Password")) = Password Then
UserFound = True
Me.Hide()
MessageBox.Show("Welcome to the System!")
frmStudents.Show()
Exit For
End If
txtUser.Text = String.Empty
txtPassword.Text = String.Empty
Next
If UserFound = False Then
MessageBox.Show("Access Denied")
End If
End Sub
Private Sub Retrieve()
objDS.Clear()
objDA.FillSchema(objDS, SchemaType.Source, "User")
objDA.Fill(objDS, "User")
End Sub
End Class
The error occurs in this line:
objDA.FillSchema(objDS, SchemaType.Source, "User") "User" is
underlined in the error
This is further info on the error shown:
An unhandled exception of type 'System.InvalidCastException' occurred
in Microsoft.VisualBasic.dll Additional information: Conversion from
string "User" to type 'Integer' is not valid

Instead of hauling down the entire users table just to verify a user get the count of records that match. Of course, in a real application, you would never store password as plain text.
Private Sub VerifyUser()
Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=Login.accdb")
Dim cmd As New OleDbCommand("Select Count(*) From Users Where [Username] = #Username and [Passwor] = #Password;", objConnection)
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = txtPassword.Test
objConnection.Open()
Dim count As Integer = CInt(cmd.ExecuteScalar())
Dim message As String = ""
If count > 0 Then
message = "Welcome"
Else
message = "Sorry"
End If
MessageBox.Show(message)
End Sub

Related

Login form in VB.Net using Access database not working

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

My Login form show OLE DB Query not working

I need to do login form in vb using role based MS Access. mdb file
but i got error Invalid Query Kindly solutions please.
Public Class login_module
'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\gasdb1.mdb
Dim loginerror As String
Dim ab As Integer
Public Function logins()
Dim DBConn As New ADODB.Connection
Dim user As New ADODB.Recordset
Dim Usernam As String
Dim UserDB As String
Dim passDB As String
Dim roleDB As String
Dim userfound As Boolean
Try
DBConn.Open("Provider = Microsoft.Jet.OLEDB.4.0;Data Source ='" & "E:\crime\crime.mdb'")
user.Open("user", DBConn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
Me.Hide()
End Try
userfound = False
logins = False
Usernam = "username ='" & TextBox1.Text & "'"
Do
Try
user.Find(Usernam)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Debug.Print(user.ToString)
So Kindly Solve also i got error operation is not allowed when the object is closed. adodb.recordset.
Public Class login_module
Private ConStr As String = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source =E:\crime\crime.mdb"
Private Function Logins(Name As String, PWord As String) As String
Dim RetVal As Object = Nothing
Dim Role As String
Dim sql = "Select Role From Users Where UserName = #Name And Password = #Password;"
Using cmd As New OleDbCommand(sql, New OleDbConnection(ConStr))
cmd.Parameters.Add("#Name", OleDbType.VarWChar).Value = Name
cmd.Parameters.Add("#Password", OleDbType.VarWChar).Value = PWord
cmd.Connection.Open()
RetVal = cmd.ExecuteScalar
End Using
If RetVal Is Nothing Then
Role = "Not Found"
Else
Role = RetVal.ToString
End If
Return Role
End Function
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim Role As String = ""
Try
Role = Logins(txtUserName.Text, txtPassword.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
Select Case Role
Case "Admin"
'Do something
Case "Supervisor"
'Do something
Case "Clerk"
'Do Something
Case Else
MessageBox.Show("No defined Role was returned.")
End Select
End Sub
End Class

My Oledb DataAdapter.Fill code is "missing parameters"

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?

InvalidOperationException was unhandled 3

I am on LogIn form in VB.Net. But I get an error when I'm trying to login.
The error shows
InvalidOperationException was unhandled
I am using a Microsoft Access database.
While I was run program it didn't say which line I had an error.
Please help me...I really appreciate you and very thankful in advance.
Below is my code:
Imports System.Data.OleDb
Public Class login
Sub koneksi()
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\bin\Debug\db.accdb;Persist Security Info=True")
conn.Open()
End Sub
Private Sub login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
koneksi()
End Sub
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
If txtstaffid.Text = "" Or txtpassword.Text = "" Then
MsgBox("Please insert your staff ID and password")
txtstaffid.Focus()
Exit Sub
Else
cmd = New OleDbCommand("select * from user where staffid='" & Rep(txtstaffid.Text) & "' and pass='" & Rep(txtpassword.Text) & "'", conn)
rd = cmd.ExecuteReader ' Error occurs here !!!
rd.Read()
If rd.HasRows Then
MsgBox("Successful Login!")
Me.Visible = False
menuUtama.Show()
menuUtama.Label1.Text = rd("role")
Clear()
Else
MsgBox("Wrong staff ID or password")
Clear()
End If
End If
End Sub
Sub clear()
txtstaffid.Text = ""
txtpassword.Text = ""
End Sub
This is my module1.vb:
Imports System.Data.OleDb
Module Module1
Public conn As OleDbConnection
Public cmd As OleDbCommand
Public rd As OleDbDataReader
Public Function Rep(ByVal kata As String) As String
Rep = Replace(kata, "'", "''")
End Function
End Module
The error shows at the line
rd = cmd.ExecuteReader

i am getting a error in open

Public Class Form4
Dim objcon As New OleDbConnection
Dim strSQL As String
Dim strconnection As String = "provider=microsoft.ACE.OLEDO.12.0;Data Source=shweta:\WindowsApplication1\Databaseapp.accdb"
Dim da As New OleDbDataAdapter
Dim ds As New DataSet
Dim attempt As Integer = 0
Private Sub btnsignin_Click(sender As Object, e As EventArgs) Handles btnsignin.Click
Dim strName = txtpassword.Text
Dim strpass = txtpassword.Text
With objcon
.Close()
If .State = ConnectionState.Closed Then
.ConnectionString = strconnection
.Open()
'{they r showing An unhandled exception of type
'System.InvalidOperationException' occurred in
' System.Data.dll }}
MsgBox("connectionstate.open", MsgBoxStyle.Information, "connected")
End If
End With
ds.Clear()
strSQL = "Select * from logintable where username='" & Txtusername.Text & "' And password =''" & txtpassword.Text '"
da = New OleDbDataAdapter(strSQL, objcon)
da.Fill(ds, "logintable")
If ds.Tables("logintable").Rows.Count <> 0 Then
MaximizeBox = True
MinimizeBox = True
Else
MaximizeBox = False
MinimizeBox = False
MessageBox.Show("invalid")
End If
Form2.Show()
Me.Hide()
End Sub
End Class
Here are errors fixed:
It works if could put Imports System.Data.OleDb before Public Class Form4.
Also, add Public Property Form2 As Object inside form4 block.
Still some part of code is missing. Could you please specify them?