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?
Related
The following code is supposed to display information from a database but there is an error (the title of this question) on the DBCmd.ExecuteNonQuery() line of code.
Does anyone know how I can resolve this problem?
• I am using VB.NET
• I am using an Access database
The code is:
Imports System.Data.OleDb
Public Class frmCheckAvailablity
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
Private Access As New DBControl
Dim QRY As String
Private DBCmd As OleDbCommand
Dim DBDR As OleDbDataReader
Public DBDA As New OleDbDataAdapter("SELECT RoomType FROM tblRoomBookings", DBCon)
Public DT As New DataTable
Public DS As New DataSet
Public DR As DataRow
Private Function NotEmpty(text As String) As Boolean
Return Not String.IsNullOrEmpty(text)
End Function
Private Sub frmCheckAvailability_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'RUN QUERY
Access.ExecQuery("SELECT * FROM tblRoomBookings ORDER BY BookingID ASC")
If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
End Sub
Private Sub frmCheckAvailability_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'NewHotelDataSet.tblRoomBookings' table. You can move, or remove it, as needed.
Me.TblRoomBookingsTableAdapter.Fill(Me.NewHotelDataSet.tblRoomBookings)
If DBCon.State = ConnectionState.Closed Then DBCon.Open() : Exit Sub
End Sub
Private Sub Search()
DBDA.Fill(DT)
txtSearch.AutoCompleteCustomSource.Clear()
For Each DBDR In DT.Rows
txtSearch.AutoCompleteCustomSource.Add(DBDR.Item(0).ToString)
Next
txtSearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
End Sub
Private Sub SearchCustomers(RoomType As String)
'ADD PARAMETERS & RUN QUERY
Access.AddParam("#RoomType", "%" & RoomType & "%")
Access.ExecQuery("SELECT * FROM tblRoomBookings WHERE RoomType LIKE #RoomType")
'REPORT & ABORT ON ERRORS
If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
QRY = "SELECT FullName FROM tblRoomBookings WHERE RoomType'" & txtSearch.Text & "'"
DBCmd = New OleDbCommand(QRY, DBCon)
DBCmd.ExecuteNonQuery()
DBDR = DBCmd.ExecuteReader
If DBDR.Read Then
txtRoomType.Text = DBDR("RoomType")
txtFirstNight.Text = DBDR("FirstNight")
txtLastNight.Text = DBDR("LastNight")
txtNoNights.Text = DBDR("NoNights")
End If
End Sub
The only place in the code that I see DBcmd.ExecuteNonQuery is in search text changed event. Do really want to run this code every time the users types a letter?
Do not create a new connection at the class (Form) level. Every time the connection is used it needs to be disposed so it can be returned to the connection pool. Using...End Using blocks handle this for you even if there is an error.
Don't call .ExecuteNonQuery. This is not a non query; it begins with Select.
You can't execute a command without an Open connection.
Never concatenate strings for sql statments. Always use parameters.
The connection is open while the reader is active. Don't update the user interface while the connection is open.
Load a DataTable and return that to the user interface code where you update the user interface.
Private ConStr As String = "Your connection string"
Private Function GetSearchResults(Search As String) As DataTable
Dim dt As New DataTable
Dim QRY = "SELECT FullName FROM tblRoomBookings WHERE RoomType = #Search"
Using DBcon As New OleDbConnection(ConStr),
DBCmd As New OleDbCommand(QRY, DBcon)
DBCmd.Parameters.Add("#Search", OleDbType.VarChar).Value = Search
DBcon.Open()
Using reader = DBCmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
Dim dtSearch = GetSearchResults(txtSearch.Text)
If dtSearch.Rows.Count > 0 Then
txtRoomType.Text = dtSearch(0)("RoomType").ToString
txtFirstNight.Text = dtSearch(0)("FirstNight").ToString
txtLastNight.Text = dtSearch(0)("LastNight").ToString
txtNoNights.Text = dtSearch(0)("NoNights").ToString
End If
End Sub
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
BACKGROUND:
I am writing an application in VB that ask for a user to login and enter in some data from product test.
PROBLEM:
I have login form that talks to a sql database and makes sure the person is supplying the right username/password. The username gets passed to the main form. From here I want to be able to fill records from our main table that was added by the user that logged in. So the user can only interact with the records they have entered.
My issue is that I am fairly confident in VB, and I took a class in SQL but I have zero idea how to search this issue to figure out the proper way. I have looked a tableadapters.fill and .getdata but it doesn't seem to be the answer.
Login Form:
Imports System.Data
Imports System.Data.SqlClient
Public Class frmLogin
Dim userName As String
Dim extrainfo As String
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If ConnectToSQL() Then
Dim frm As New frmQuality(userName, extrainfo)
Me.Hide()
frm.Show()
Me.Close()
End If
End Sub
Private Function ConnectToSQL() As Boolean
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim dbPassword As String
Dim enteredPasswrd As String
' Dim userName As String
Try
con.ConnectionString = "Data Source "
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT UserName, Password, extrainfo FROM users WHERE (UserName like '" & "%" & txtUsername.Text.ToLower() & "%" & "' )"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
'Do something here
dbPassword = lrd("Password").ToString()
userName = lrd("UserName").ToString()
extrainfo = lrd("assigned_ei").ToString()
enteredPasswrd = txtPassword.Text()
If dbPassword.Trim() = enteredPasswrd And userName.TrimEnd(vbCrLf.ToCharArray).ToLower() = txtUsername.Text.ToLower() Then
Return True
'Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
Else
MsgBox("Incorrect Password")
End If
End While
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
'Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
Return False
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
End Function
Private Sub frmLogin_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtUsername.Focus()
End Sub
End Class
Main form
Pic:https://i.imgur.com/LY6wjQZ.png
Code
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source = location"
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT * FROM table WHERE adduser = '" & user & "'"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
' i see that above can pull the info
' but how do I get it into the form?
End While
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
End Sub
I have a database with the main table has 9 columns of information. One being called addUser which is the user that logs in and enters data. I need to have when they log in that it only displays their records. I do not want to directly attach to the textbox. As you can see from the form you can hit move around see from first to last record of the owner. I need to be able to browse the records. A person logs in and could 1 to 10 or more records. This application will let them move or create a new record. How do I do this?
I think you are asking how to read data from a DataReader into a form field, such as a textbox. If so, this is the general structure of a line which will read from one of the returned database fields ("FieldName1") into one of the form fields ("TextBox1"). You just need to know your field names, and the IDs of the controls in your form.
TextBox1.Text = lrd("FieldName1").ToString()
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
I got the error "invalid cast exception unhandled." I'm using SQL Server 2008 and Visual Studio 2008. I get conversion from String "Jack" to type Boolean is not valid.
See the code of my form below:
Imports System.Boolean
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim username As String
Dim pswd As String
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim reader As SqlDataReader
username = txt_username.Text
pswd = txt_password.Text
txt_username.Text = Focus()
txt_password.Visible = "False"
Try
conn = New SqlConnection("data source=TAMIZHAN\SQLEXPRESS;persistsecurity info=False;initial catalog=log;User ID=sa;Password=123");
cmd = New SqlCommand("Select usename,passw from Userlog where usename='" + username + "' & passw='" + pswd + "'")
conn.Open()
reader = cmd.ExecuteReader()
If (String.Compare(pswd and '"+passw+"')) Then
MsgBox("Success")
End If
If (reader.Read()) Then
MsgBox("Login success")
End If
conn.Close()
Catch ex As Exception
MsgBox("Error"+ex.Message());
End Try
End Sub
End Class
The string.Compare returns an Integer not a boolean and should be called in this way
If (String.Compare(pswd,passw) = 0) Then
MsgBox("Success")
End If
Please see the references on MSDN
However your code has many problems as it stands now:
You are using string concatenation to build your sql text
(SqlInjection, Quoting problems).
You don't use the Using statement (connection remains open in case of
exception).
The compare logic seems to be absolutely not needed.