InvalidOperationException was unhandled 3 - vb.net

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

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

next button shows this error {"Conversion from string ""Error"" to type 'Integer' is not valid."}

Imports System.Data
Imports System.Data.OleDb
Module Module1
Public Con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zmare\Desktop\Database\Unique Center Quetta\Unique Center Quetta\bin\Debug\DB.mdb")
Public cmd As OleDbCommand
Public dad As OleDbDataAdapter
Public dst As New DataSet
Public currentrow
End Module
Private Sub showdata(ByVal currentrow)
Try
txtID.Text = dst.Tables("Invoice").Rows(currentrow)("ID")
txtInvoiceNo.Text = dst.Tables("Invoice").Rows(currentrow)("Invoiceno")
txtidate.Text = dst.Tables("Invoice").Rows(currentrow)("Idate")
txtdistributor.Text = dst.Tables("Invoice").Rows(currentrow)("Distributor")
txtaddress.Text = dst.Tables("Invoice").Rows(currentrow)("Address")
txtstregno.Text = dst.Tables("Invoice").Rows(currentrow)("Stregno")
txtcname.Text = dst.Tables("Invoice").Rows(currentrow)("Cname")
txtddate.Text = dst.Tables("Invoice").Rows(currentrow)("Ddate")
txtcaddress.Text = dst.Tables("Invoice").Rows(currentrow)("caddress")
Catch ex As Exception
MsgBox(ex.Message, "Error")
End Try
End Sub
Private Sub btnnext_Click(sender As Object, e As EventArgs) Handles btnnext.Click
If currentrow = dst.Tables("Invoice").Rows.Count - 1 Then
MsgBox("You are on Last Record", MsgBoxStyle.Exclamation)
Else
CurrentRow += 1
ShowData(CurrentRow)
End If
End Sub

Need help editing Customer Info in VB.net

I am trying to edit customers using my C# project to learn how to implement this code in VB.net. The project was successful in adding customers, but when it got to editing customers, things got a bit more complicated because I needed to get the id of the row selected and pass it to a string. I have the MainForm.vb which could open CustomerForm.vb when I click on 'Edit'. When CustomerForm.vb opens, it failed to show the customer's info. I am not sure if FillDataTable() function is necassary, I would like to know if there is an improvement to this.
CustomerForm.vb
Imports System.Data.SqlClient
Public Class CustomerForm
Private objConnection As SqlConnection
Public objDataTable As DataTable = New DataTable()
Public objSqlCommand As SqlCommand = New SqlCommand()
Public editMode As Boolean = False
Public id As String = ""
Public FName As String = ""
Public LName As String = ""
Public PhNumber As String = ""
Public ReadOnly Property Connection As SqlConnection
Get
Return Me.objConnection
End Get
End Property
Dim CS As String = ("server=CASHAMERICA;Trusted_Connection=yes;database=ProductsDatabase2; connection timeout=30")
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If editMode = False Then
If txtFirstName.Text = "" Then
MessageBox.Show("First Name Is required")
ElseIf txtLastName.Text = "" Then
MessageBox.Show("Last Name Is required")
Else
Dim con As New SqlConnection(CS)
con.Open()
Dim cmd As New SqlCommand("INSERT INTO Customers(FIrstName,LastName,PhoneNumber) VALUES(#FName, #LName, #PhNumber)", con)
cmd.Parameters.AddWithValue("#FName", txtFirstName.Text)
cmd.Parameters.AddWithValue("#LName", txtLastName.Text)
cmd.Parameters.AddWithValue("#PhNumber", txtPhoneNumber.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Customer has been added!")
con.Close()
End If
ElseIf editMode = True Then
If txtFirstName.Text = "" Then
MessageBox.Show("First Name Is required")
ElseIf txtLastName.Text = "" Then
MessageBox.Show("Last Name Is required")
Else
Dim con As New SqlConnection(CS)
con.Open()
Dim cmd As New SqlCommand("UPDATE Customers SET FIrstName = #FName, LastName = #LName, PhoneNumber = #PhNumber WHERE Id = #Id", con)
cmd.Parameters.AddWithValue("#Id", id)
cmd.Parameters.AddWithValue("#FName", txtFirstName.Text)
cmd.Parameters.AddWithValue("#LName", txtLastName.Text)
cmd.Parameters.AddWithValue("#PhNumber", txtPhoneNumber.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Customer has been edited.")
con.Close()
End If
End If
Catch ex As Exception
MessageBox.Show(Me, ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.Close()
End Sub
Private Sub CustomerForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If editMode = False Then
GetId()
Else
textId.Text = id
txtFirstName.Text = FName
txtLastName.Text = LName
txtPhoneNumber.Text = PhNumber
End If
End Sub
Private Sub GetId()
Dim con As New SqlConnection(CS)
con.Open()
Dim cmd As New SqlCommand("SELECT MAX(id)+1 FROM Customers")
textId.Text = FillDataTable().Rows(0)(0).ToString()
If textId.Text = "" Then
textId.Text = "1"
End If
End Sub
Public Property CommandText As String
Get
Return CommandText
End Get
Set(ByVal value As String)
CommandText = value
End Set
End Property
Public Sub OpenDBConnection()
objConnection = New SqlConnection(CS)
objConnection.Open()
End Sub
Public Sub CreateCommandObject()
objSqlCommand = objConnection.CreateCommand()
objSqlCommand.CommandText = CommandText
objSqlCommand.CommandType = CommandType.Text
End Sub
Public Function FillDataTable() As DataTable
objDataTable = New DataTable()
objSqlCommand.CommandText = CommandText
objSqlCommand.Connection = objConnection
objSqlCommand.CommandType = CommandType.Text
objDataTable.Load(objSqlCommand.ExecuteReader())
objConnection.Close()
Return objDataTable
End Function
Public Sub CloseConnection()
If objConnection IsNot Nothing Then objConnection.Close()
End Sub
End Class
MainForm.vb
Imports System.Windows.Forms.LinkLabel
Public Class MainForm
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
End Sub
Private Sub AddToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddToolStripMenuItem.Click
CustomerForm.ShowDialog()
End Sub
Private Sub AddToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles AddToolStripMenuItem1.Click
ProductForm.ShowDialog()
End Sub
Private Sub ViewProductsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewProductsToolStripMenuItem.Click
ManageProductsForm.ShowDialog()
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
AboutForm.Show()
End Sub
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ProductsDatabase2DataSet1.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.ProductsDatabase2DataSet1.Customers)
End Sub
Private Sub gridCustomers_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gridCustomers.MouseUp
Try
Dim f As CustomerForm = New CustomerForm()
f.editMode = True
Dim rowIndex As Integer = gridCustomers.CurrentCell.RowIndex
f.id = gridCustomers.Rows(rowIndex).Cells("colId").Value.ToString()
f.FName = gridCustomers.Rows(rowIndex).Cells("colFirstName").Value.ToString()
f.LName = gridCustomers.Rows(rowIndex).Cells("colLastName").Value.ToString()
f.PhNumber = gridCustomers.Rows(rowIndex).Cells("colPhoneNumber").Value.ToString()
f.Show()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub gridCustomers_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles gridCustomers.CellContentClick
Dim f As CustomerForm = New CustomerForm()
f.ShowDialog(Me)
f.editMode = True
End Sub
End Class
Error Message:
Customer Info not displayed:
As mentioned, it seems like you have several things potentially going on.
The first thing I would change is your public sql objects. You don't need them to be public. It also increases the chances for issues if you're using the same objects in multiple places.
SqlCommand, SqlConnection, and SqlDataAdapters can be immediately disposed of (in most cases) as soon as they are used.
One easy method to handling all of that is to throw everything inside of a USING block.
Dim sqlResult As New Datatable()
Using cn As New SqlConnection("Connection String here"),
cmd As New SqlCommand(sql, cn),
adapt As New SqlDataAdapter(cmd)
cn.Open()
'Handle stored procedure vs select options
If sql.Contains("SELECT") Then
cmd.CommandType = CommandType.Text
Else
cmd.CommandType = CommandType.StoredProcedure
End If
'If parameters passed, else comment out
cmd.Parameters.AddWithValue("#parameterName", parameterValue)
sqlResult = New DataTable(cmd.CommandText)
adapt.Fill(sqlResult)
End Using
Now all your objects are disposed of as soon as your datatable is filled.
*This example uses a datatable, but it is the same idea for anything interacting with sql objects.
If implemented, you may find out that some objects weren't being disposed of or initialized properly.
Another method for testing where things are going wrong is to query the states of the SQL objects before or around the error to see if something isn't set correctly or is uninitialized.

Error: "No value given for one or more required parameters"

Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim cnnOLEDB As New OleDbConnection
Dim cmdOLEDB As New OleDbCommand
Dim cmdInsert As New OleDbCommand
Dim cmdDelete As New OleDbCommand
Dim cmdUpdate As New OleDbCommand
Dim conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\Steven\Desktop\Database.accdb"
Private Sub searchbtn_Click(sender As Object, e As EventArgs) Handles searchbtn.Click
If ssearch.Text <> "" Then
cmdOLEDB.CommandText = "SELECT StudentID from Students Where TP = " & CInt(ssearch.Text)
cmdOLEDB.Connection = cnnOLEDB
Dim rd As OleDbDataReader = cmdOLEDB.ExecuteReader()
If rd.Read = True Then
Form2.Show()
Form2.TextBox1.Text = rd(0).ToString
Else
MessageBox.Show("Information not found in Database")
End If
rd.Close()
End If
Me.Hide()
Form2.Show()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cnnOLEDB.ConnectionString = conn
cnnOLEDB.Open()
End Sub
Private Sub ssearch_TextChanged(sender As Object, e As EventArgs) Handles ssearch.TextChanged
End Sub
Private Sub insertbtn_Click(sender As Object, e As EventArgs) Handles insertbtn.Click
If ssearch.Text <> "" Then
cmdInsert.CommandText = "INSERT INTO Students (StudentID) VALUES (" & ssearch.Text & ");"
cmdInsert.CommandType = CommandType.Text
cmdInsert.Connection = cnnOLEDB
cmdInsert.ExecuteNonQuery()
MsgBox(ssearch.Text & " " & "Record inserted.")
ssearch.Text = ""
Else
MsgBox("Please Enter Student ID")
End If
cmdInsert.Dispose()
End Sub
End Class
As you can see i can insert data into the database but I can't search it. When I run it it show errors on Dim rd As OleDbDataReader = cmdOLEDB.ExecuteReader()
saying:
No value given for one or more required parameters visual basic error
What was my mistake?

login form using ms access in vb.net

I'm creating a login form for vb.net using ms access 2003 as database. But it only checks for the username and bypasses the password. Meaning that if the username is correct and the password doesn't jive with the username, the user can still enter the system. Here is my code:
Try
Dim NoAcc As String
Dim NoAccmod2 As String
Dim NoPas As String
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from admintable where AdminName= '" & TextBox4.Text & "' ", cn)
cn.Open()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
NoAcc = rdr("AdminName")
NoPas = rdr("AdminPass")
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
adminview.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox4.Clear()
TextBox3.Clear()
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
How do I do it so that it checks both username and password?
You are using a single line IF .. THEN :
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
so the next line will always be executed:
adminview.Show()
you have to rearrange your IF .. THEN conditions
I will share about login system in vb.net using binding navigator that less of coding. just following the link below!
http://www.tesear.com/2011/09/login-system-in-vbnet.html
You could have BOTH the uname and pword in the database and "WHERE" on both, if you get no record back, then you have your answer.
Try using System.String.Compare(String str1,String str2, Boolean ) As Integer like:
If (System.String.Compare(TextBox4.Text, NoAcc, false) And System.String.Compare(TextBox3.Text, NoPas, false)) Then NoAccmod2 = NoAcc
here is the code:
Imports System.Data
Imports System.Data.OleDb
Public Class Form5
Inherits System.Windows.Forms.Form
Dim mypath = Application.StartupPath & "\login.mdb"
Dim mypassword = ""
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath & ";Jet OLEDB:Database Password=" & mypassword)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Dim sql = "SELECT UserID ,PassID FROM MYTAB WHERE USERID='" & TextBox1.Text & "' AND PASSID='" & TextBox2.Text & "'"
cmd = New OleDbCommand(sql, conn)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Try
If dr.Read = False Then
MessageBox.Show("Authentication failed...")
Me.Show()
Else
MessageBox.Show("Login successfully...")
Dim frmDialogue As New Form11
frmDialogue.ShowDialog()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Close()
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
Me.Hide()
Dim frmDialogue As New Form1
frmDialogue.ShowDialog()
End Sub
Private Sub Form5_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Dim frm As New Form1
frm.Show()
End Sub
End Class
Try
Dim NoAcc As String
Dim NoPas As String
Dim rdr As OleDbDataReader
Dim cnn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\mobilestore.accdb;Persist Security Info=False;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from logindata where Username= '" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", cnn)
'NoAcc = TextBox1.Text
'NoPas = TextBox2.Text
cnn.Open()
rdr = cmd.ExecuteReader
If (rdr.Read()) Then
NoAcc = rdr("Username")
NoPas = rdr("password")
If (TextBox1.Text = NoAcc And TextBox2.Text = NoPas) Then
Adminpage.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
End Sub