Validating user input against MS Access Database

nick8012

Member
Joined
Sep 19, 2007
Messages
5
Programming Experience
Beginner
Hello I am new here and I am having trouble with validating user input against a Microsoft Access Database.

I am developing an application in which a user enters a user name and password.

What I need to do is somehow validate the input against my access database. Right now I am only worried about validating the username.

Here is the code that I have so far:

VB.NET:
Private Sub btnSignOn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSignOn.Click
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim sql As String
Dim myname As String
Dim password As String
myname = Me.txtUsrName.Text
password = Me.txtPasswd.Text

Try
'provider to be used when working with access database
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0 ;DataSource=C:\DocumentsandSettings\nick\MyDocumen ts\Capstone\Users.mdb;")
cn.Open()

cmd = New OleDbCommand("select * from Personal where UserName ='" & myname & "'", cn)

Dim count As Integer
count = cmd.ExecuteScalar

If count = 0 Then
MessageBox.Show("Denied")
Else
MessageBox.Show("Accepted")
End If
cn.Close()

Catch this As NullReferenceException
this.GetBaseException()
MessageBox.Show("Exception thrown")
End Try

End Sub
If I enter a username that is not in the database everything works fine.
However if I enter a username that is in the database the I keep getting this error.

An unhandled exception of type 'System.InvalidCastException' occurred in system.windows.forms.dll

Additional information: Cast from string "nickS" to type 'Integer' is not valid.

I tried changing this line: count = cmd.ExecuteScalar
to: count = Cint(cmd.ExecuteScalar)
but still the same error keeps coming up.

I just need a way to validate the input against the MS Access database.
Any help would be Greatly appreciated. Thanks
 
Last edited by a moderator:
OleDbCommand.ExecuteScalar Method:
Return Value
The first column of the first row in the result set, or a null reference if the result set is empty.
so you can check
If cmd.ExecuteScalar Is Nothing Then MessageBox.Show("Denied")
 
Thanks JohnH for the reply.
That worked great!!
I also found another way to do this.

dr = cmd.ExecuteReader
If dr.Read() Then
MessageBox.Show("Accepted")
Else
MessageBox.Show("Denied")
End If
 
Back
Top