i don't know what's wrong with it can you analyze if possible - system

I have based my codes from my professors. I typed the right username and password but it keeps on saying invalid user. The name of the table is also correct. I don't know why it keeps on saying it's an invalid user kindly help me please.
If Len(Trim(txtUsername.Text)) = 0 Then
MessageBox.Show("Please enter user name", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtUsername.Focus()
Exit Sub
End If
If Len(Trim(txtPassword.Text)) = 0 Then
MessageBox.Show("Please enter password", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtPassword.Focus()
Exit Sub
End If
Dim query As String = "SELECT * FROM Users"
Dim dt As New DataTable
ExecuteQuery(query)
Dim ctr As Integer
If dt.Rows.Count > 0 Then
If (dt.Rows(ctr)("Username")) = txtUsername.Text Then
If (dt.Rows(ctr)("Password")) = txtPassword.Text Then
frmMainMenu.Show()
Me.Hide()
End If
Else
MsgBox("Incorrect password")
txtPassword.Text = ""
txtPassword.Focus()
End If
Else
MsgBox("Invalid user")
txtPassword.Text = ""
txtUsername.Text = ""
txtUsername.Focus()
End If

You are never initializing the dt DataTable. So a new DataTable will have 0 rows, and you will fall into the Else of If dt.Rows.Count > 0. I presume you had intended to have dt be the DataTable that results from the ExecuteQuery statement, but as you are neither passing dt in nor assigning a result from ExecuteQuery to the dt variable, it is still blank.
Not knowing what ExecuteQuery does, I would imagine it should be either
ExecuteQuery(query, dt)
or
dt = ExecuteQuery(query)
After which point you might fall into the intended username/password comparison block, if there are actually rows in the Users table.
However your matching still will not work unless the matching record is the first in the DataTable, as you never actually iterate/increment ctr.

this is my codes for ExecuteQuery()
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\nikko\Documents\Visual Studio 2010\Projects\PayrollSystemThesis\PayrollSystemThesis\bin\Debug\Thesis.accdb"
Public Function ExecuteQuery(ByVal query As String) As DataTable
Try
Dim dbCon As New OleDbConnection(connectionString)
Dim dbDA As New OleDbDataAdapter(query, dbCon)
Dim dbCB As New OleDbCommandBuilder(dbDA)
Dim dbDT As New DataTable
dbDA.Fill(dbDT)
Return dbDT
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
End Function
it reads sql statements.

Related

After entering your login details, nothing happens

When I enter the username and password, and click on login, nothing happens, as if there is no code. What is wrong with my code?
Dim Username As String = ""
con.Open()
Dim sql As String
Dim i As Boolean
sql = "SELECT [UserName], [Password] FROM tblLogin WHERE
[UserName]=? AND [Password]=?;"
If txtUsername.Text = "" Or txtPassword.Text = "" Then
MsgBox("Please enter your credentials")
Dim cmd = New OleDbCommand(sql, con)
i = cmd.ExecuteNonQuery
If (i = True) Then
MsgBox("Login successful")
frmMain.Show()
Else
MsgBox("Login failed")
End If
cmd = Nothing
con.Close()
There is a missing End If in this code snippet. I assume that it appears after the code you are showing us.
If txtUsername.Text = "" Or txtPassword.Text = "" Then
MsgBox("Please enter your credentials")
Dim cmd = New OleDbCommand(sql, con)
i = cmd.ExecuteNonQuery
If (i = True) Then
MsgBox("Login successful")
frmMain.Show()
Else
MsgBox("Login failed")
End If
cmd = Nothing
con.Close()
End If '<== this one is missing
This means that the query is only executed when username or password are empty according to If txtUsername.Text = "" Or txtPassword.Text = "" Then.
The code should look like this:
If txtUsername.Text = "" Or txtPassword.Text = "" Then
MsgBox("Please enter your credentials")
Else
Dim cmd = New OleDbCommand(sql, con)
Dim rowsAffected = cmd.ExecuteNonQuery
If rowsAffected > 0 Then
MsgBox("Login successful")
frmMain.Show()
Else
MsgBox("Login failed")
End If
cmd = Nothing
con.Close()
End If
Added an Else.
Aslo, ExecuteNonQuery returns an Integer telling you how many records have been affected. It does not return a Boolean.
And you seem to be creating and opening the connection before the if-statements decides whether the query will be executed. Creating and opening the connection should probably happen in the Else part as well. You should embed the connection in a Using Statement. See also this answer to creating a ConnectionString in vb.net
As #jmcilhinney suggests in a comment, debug your code! Have a look at: Tutorial: Learn to debug Visual Basic code using Visual Studio

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

Update a record if it already exists in access with vb

I'm trying to check if a client is already signed in. if he is, then the button will sign him out instead of adding a new record altogether and I'm struggling to find a solution.
this is the current code I'm using:
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
Dim cmd As New OleDbCommand
' cnn = cnn
Try
If Not cnn.State = ConnectionState.Open Then 'open the database connection
cnn.Open()
End If
If txtClientName.Text = Nothing Then 'check to see if the name field is empty
MsgBox("Please enter a name to sign in")
txtClientName.Focus()
ElseIf txtDateTime.Text = Nothing Then ' checks if timeslip is empty
MsgBox("Please enter a valid time to sign in")
txtDateTime.Focus()
Else 'if no fields are empty proceed with code
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO LogSheet (ClientName, SignInTime, CurrentDate)" &
"VALUES(?, ?, ?)"
cmd.Parameters.AddWithValue("#p1", txtClientName.Text.ToString.ToUpper)
cmd.Parameters.AddWithValue("#p2", txtDateTime.Text)
cmd.Parameters.AddWithValue("#p3", Date.Now().ToShortDateString)
cmd.ExecuteNonQuery()
RefreshData()
txtClientName.Clear()
txtDateTime.Clear()
End If
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
cnn.Close()
End Try
End Sub
there is no validation there, but ive tried many different codes with no luck..
I simply want the script to check, if client is signed in, then give an error "Client already signed in" else if he signs out, just update the signout field
thanks
This is an image of what my program is1
Update the structure of your Database Table (LogSheet) to include the following fields. ClientName,SignInTime,SignInRelation,SignOutTime,SignOutRelation,CurrentDate
If the client is signed in then the SignInTime for today (CurrentDate) will have a value, you can then populate the value for SignOutTime.
This is one possible way you could code it:
This code is untested, but you should get the idea.
Sub BtnSignIn_Click()
If IsUserLoggedIn(txtClientName.Text) = True Then
'Client has been logged in already. Do Action.
Else
'Client has not been logged in today. Do Action.
End If
End Sub
Function IsUserLoggedIn(UserName As String) As Boolean
Dim sql = "Select SignOutTime From LogSheet Where CurrentDate=#D AND ClientName=#C"
Try
Using cnn As New OleDbConnection
Using cmd As New OleDbCommand(sql, cnn)
cnn.Open()
cmd.Parameters.AddWithValue("#D", Today.Date.ToShortDateString)
cmd.Parameters.AddWithValue("#C", UserName)
Dim result = cmd.ExecuteScalar
If result Is Nothing OrElse result Is DBNull.Value OrElse String.IsNullOrEmpty(result.ToString) Then
Return False
Else
Return True
End If
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "Error: " & System.Reflection.MethodBase.GetCurrentMethod.Name, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Function
You should insert DateTime values:
cmd.Parameters.AddWithValue("#p2", DateTime.Parse(txtDateTime.Text))
cmd.Parameters.AddWithValue("#p3", DateTime.Today)

Detecting if data exists for OleDB COUNT query

I'm trying to pull data from ACCESS database.
As it is, the code works, and gives no errors...
However, I can't seem to be able to display a messagebox if the record doesn't exist. It simply returns an empty string.
Using dbCon = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source = '" & Application.StartupPath & "\Res\T500G.accdb'")
dbCon.Open()
Dim Query1 As String = "SELECT SUM(Total) FROM [T500] WHERE Pro=#Pro"
Dim cmd1 As OleDb.OleDbCommand = New OleDbCommand(Query1, dbCon)
cmd1.Parameters.AddWithValue("#Pro", ComboBoxBP.SelectedItem.ToString)
Dim reader As OleDb.OleDbDataReader
reader = cmd1.ExecuteReader
While reader.Read()
TextBox1.Text = reader.GetValue(0).ToString
End While
reader.Close()
dbCon.Close()
End Using
I've tried using If reader.hasrows then display result in textbox, else show messagebox etc, but it doesn't work.
If reader.HasRows Then
While reader.Read()
TextBox1.Text = reader.GetValue(0).ToString
End While
Else
MessageBox.Show("asd")
End If
If I remove the .ToString from reader.GetValue(0) I get an error if the selected item from the combobox doesn't exist in the database. Cannot convert DBNull to integer or something.
So my question is, how to display a messagebox if the record "#Pro" doesn't exist?
Thanks~
Fixed(Workaround) with this
Dim ValueReturned As String
While reader.Read()
ValueReturned = reader.GetValue(0).ToString
If ValueReturned = "" Then
MessageBox.Show("Not Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
MetroTextBox1.Text = ValueReturned
End If
End While
Using OleDbDataReader is suboptimal for your query because it is never going to return a set of records to traverse:
Dim sql = "SELECT SUM(...=#p1"
' rather than sprinkling you connection string all over
' the app, you can make a function returning one
Using conn As OleDbConnection = GetConnection(),
cmd As New OleDbCommand(sql, GetConnection())
conn.Open())
' ToDo: Check that ComboBoxBP.SelectedItems.Count >0 before this
cmd.Parameters.AddWithValue("#p1", ComboBoxBP.SelectedItem.ToString)
' execute the query, get a result
Dim total = cmd.ExecuteScalar
' if there is no matches, OleDb returns DBNull
If total Is System.DBNull.Value Then
' no matches
MessageBox.Show("No matching records!"...)
Else
MessageBox.Show("The Total is: " & total.ToString()...)
End If
End Using ' disposes of the Connection and Command objects
Alteratively, you could use If IsDBNull(total) Then.... If you want, you can also convert it:
Dim total = cmd.ExecuteScalar.ToString()
' DBNull will convert to an empty string
If String.IsNullOrEmpty(total) Then
MessageBox.Show("No Soup For You!")
Else
...
End If
You could change your query to (this is for SQL-Server):
IF EXISTS (SELECT * FROM [T500] WHERE Pro = #Pro) SELECT SUM(Total) FROM [T500] WHERE Pro = #Pro ELSE SELECT 'Not Found'
And change your code to:
Dim ValueReturned As String
While reader.Read()
ValueReturned = reader.GetValue(0).ToString
End While
If ValueReturned Is Nothing OrElse ValueReturned = "Not Found" Then
MessageBox.Show("Not Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
TextBox1.Text = ValueReturned
End If

Why does my code only read first row in database?

Dim con As New SqlConnection
con.ConnectionString = "Data Source=(local);Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * FROM login where Admin = #Admin AND Password = #Password ", con)
'Set up parameters for the sqlcommand
cmd.Parameters.AddWithValue("#Admin", comb.Text)
cmd.Parameters.AddWithValue("#Password", Txtpass.Text)
'If the username or password is empty then throw an error
If comb.Text = String.Empty Then
MessageBox.Show("Please choose the username.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
ElseIf Txtpass.Text = String.Empty Then
MessageBox.Show("Please enter the password.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Try
'Open the connection and declare an sqlreader
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader
'If our reader has one or more rows then read those rows and compare the text
If reader.HasRows = True Then
reader.Read()
Dim ReadUserName As String
Dim ReadUserID As String
ReadUserID = reader(3) 'This is the first field returned, most likely UserID
ReadUserName = reader(1) 'This is the second field returned
'If the username and password match then it's a success
If comb.Text = reader("Admin").ToString And Txtpass.Text = reader.Item("Password").ToString Then
MessageBox.Show("Login successful" & ReadUserName)
Else
'If they don't match than throw an error
MessageBox.Show("Login Failed." & Environment.NewLine & _
"UserName and Password are casesensitive.", _
Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End If
Catch ex As Exception
MessageBox.Show(ex.ToString, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
con.Close()
End Try
End If
You're telling your code to read one row:
If reader.HasRows = True Then
reader.Read()
If you want to read all rows from your SqlDataReader, you need to use a loop (here in C#):
while (reader.Read())
{
..... (read the individual values for the current row) ......
}
The .Read() call will return true, as long as a row has been read from the SqlDataReader - now fetch the data from the row, store it or process it - whatever you need to do - and then your next call to reader.Read() checks if another row can be read. If so: repeat your processing.
If reader.Read() return false, then all rows have been read and you're done.
If command runs the code only once and read one row. So use while loop to read all the line
If reader.HasRows = True Then
While reader.Read()
Dim ReadUserName As String
Dim ReadUserID As String
ReadUserID = reader(3) 'This is the first field returned, most likely UserID
ReadUserName = reader(1) 'This is the second field returned
'If the username and password match then it's a success
If comb.Text = reader("Admin").ToString And Txtpass.Text = reader.Item("Password").ToString Then
MessageBox.Show("Login successful" & ReadUserName)
Else
'If they don't match than throw an error
MessageBox.Show("Login Failed." & Environment.NewLine & _
"UserName and Password are casesensitive.", _
Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End While ' I don't know much of vb.net'
End If