Modifying button properties - vb.net - vb.net

What I am trying to achieve is, when the user recognised in the table with week 1 "found", the button should turn red, disable functionality and change the button content. However an error message comes up as soon as I enter the screen saying:
"fatal error encountered during command execution".
If anyone could possibly help I would much appreciate it in advance :)
Private Sub LondonC_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim connStr As String = ""
Dim Query As String
Query = "select week1 from table where username= #name AND week1 = 'found'"
Dim username = Login.txtusername.Text
Dim connection As New MySqlConnection(connStr)
COMMAND = New MySqlCommand(Query, connection)
connection.Open()
Dim READER As MySqlDataReader
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "select * from table where username='" & Login.txtusername.Text & "'"
Dim week1 As String
week1 = READER("week1")
Button4.BackColor = Color.Red
Button4.Enabled = False
Button4.Text = "Completed"
End If
Catch ex As Exception
MsgBox("Error")
End Try
End Sub

You defined username string variable but forgot to add username parameter in your query.
Add this lines to your code:
Dim username = Login.txtusername.Text
Query = Query.Replace("#name", username)

Related

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

simple login form error VB 2010

I've search a lot of resources and couldn't fix it.
My problem is when I click the button event the next form doesn't show and also I want to close my login form at the same time.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim firstname As String = ""
Dim lastname As String = ""
Dim ara As Boolean = False
cn = New OleDbConnection(con)
cn.Open()
Dim user As String
Dim pass As String
user = TextBox1.Text
pass = TextBox2.Text
With cmd
.Connection = cn
.CommandText = "Select * from users WHERE username='" & user & "' AND password='" & pass & "'"
.ExecuteNonQuery()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
ara = True
While rdr.Read()
firstname = rdr("firstname").ToString
lastname = rdr("lastname").ToString
lib_name = firstname + lastname
End While
If ara = True Then
Form2.Show()
Me.Close()
x = True
Else
MsgBox(" Access Denied!" + Environment.NewLine + "Sorry, username or password is incorrect!")
End If
End If
End With
cn.Close()
cmd.Dispose()
1 : You are opening the gates of SQL INJECTION. Read more . Instead of passing values directly in your query, pass parameters first and use them later(For unknown reason, the code formatting is not working below) :
Dim cmd as New OleDbCommand("Select * from users WHERE username=#user AND password=#pass" , con)
With cmd
.Parameters.Add("#user", OleDbType.Varchar).Value = user
.Parameters.Add("#user", OleDbType.Varchar).Value = password
End With
2 : Your If statement will only work IDateReader.HasRows returns true and if ara=True which is unnecessary. .HasRows is a boolean, you don't need to create another boolean and pass the value to it. However, the rest of your code will only execute if your conditions match
3 : Form1.Close and AnotherForm.Show will never work if in your Project Proerties , Shutdown Mode is set to On main window close(by default). Either change it to On Explicit window close or On last window close or change
Me.CLose To
Me.Hide
4 : In order to reduce too much code , you can use Using Statement :
Using cmd as New SqlCommand("Select * from users WHERE username=#user AND password=#pass" , con)
'''codes here
End Using
''Now no need to call cmd.Dispose
Hope this helps :)

LogIn form with user and admin using VB.net and Mysql

I want to get the privilege if it's admin or encoder but with this code I can't get any value... this is my code please help me
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
cn = New MySqlConnection
cn.ConnectionString = "server=localhost; userid=root; database=dp_inventory;"
Dim reader As MySqlDataReader
Try
cn.Open()
Dim sql As String
sql = "Select from dp_inventory.user_account where employeeID='" & UsernameTextBox.Text & "' and password='" & PasswordTextBox.Text & "' "
cmd = New MySqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
Dim users As String
users = "select privilege from user_account where employeeID='" & UsernameTextBox.Text & "'"
If count = 1 Then
If users = "admin" Then
frmAdminMain.Show()
ElseIf users = "encoder" Then
MainForm.Show()
End If
ElseIf count > 1 Then
frmAdminMain.Show()
Else
MsgBox("tryy again")
End If
Catch ex As Exception
MsgBox("Try again")
End Try
End Sub
There are quite a few errors in this code you wrote. Your first issue is you are simply trying to count without actually using a Sql counter.
Take a look at a code snippet from one of my applications here for a general idea
SelectStr = "SELECT MagPieces_Number,MagOperators_Number,MagFactor_Number,MagTotal_Number" & _
" FROM Parts_Mag WHERE Quote_Number_Id = #QuoteId and Quote_Rev_Id = #RevId and Part_Number_Id = #PartID and Part_Numeral_Id = #PartNumeral and SiteLocation = #Site"
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#QuoteId", QuoteId)
SqlDataCmd.Parameters.AddWithValue("#RevId", RevId)
SqlDataCmd.Parameters.AddWithValue("#PartId", PartNumber)
SqlDataCmd.Parameters.AddWithValue("#PartNumeral", PartNumeral)
SqlDataCmd.Parameters.AddWithValue("#Site", SiteLocation)
SqlReader = SqlDataCmd.ExecuteReader
While SqlReader.Read
MagPieces = SqlReader("MagPieces_Number").ToString
MagOperators = SqlReader("MagOperators_Number").ToString
MagFactor = SqlReader("MagFactor_Number").ToString
MagTotal = SqlReader("MagTotal_Number").ToString
End While
MagParticle.txtPiecesPerHour.Text = MagPieces
MagParticle.txtOperators.Text = MagOperators
MagParticle.txtMatFactor.Text = MagFactor
MagParticle.labMagTotal.Text = MagTotal
Catch ex As Exception
ErrorMessage(ex.message)
SqlReader.Close()
End Try
SqlReader.Close()
If you are simply looking for if your select statement has "Admin" or "Encoder" at the end, it would simply be something like this:
Dim empId as String = UsernameTextbox.Text
Dim SelectStr as String = "Select privilege from dp_inventory.user_account where employeeID=#empId
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#empId", empId)
Then read it with a reader. Once you have the general idea you should be able to take it from there! Im not quite sure why you need the count to begin with so you may want to just negate that portion out and simply read from your table based on the ID

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

Cheking duplicate name and insert user vb.net

I am doing a form where the user is writing his username and choose from a button list. Before the insert i need to check if the username is already existed or not. The server side code is:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
'Duplicate username
Dim username As String = tbUsername.Text.Trim()
Dim tempUser As Byte = CByte(rblDept.SelectedIndex)
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim haha As DataTable = New DataTable()
Using adapter = New SqlDataAdapter(query1, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
adapter.Fill(haha)
If haha.Rows.Count <> 0 Then
lblmessage.Text = "Error! user name is already exist"
Return
End If
End Using
'Insert new user
Dim query As String = "Insert into Intranet.dbo.Gn_ISCoordinators (cUserName,lDeptUser) Values ('" & username & "'," & tempUser & ")"
Dim hehe As DataTable = New DataTable()
Using adapter1 = New SqlDataAdapter(query, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
adapter1.Fill(hehe)
lblmessage.Text = "User has been added"
End Using
End Sub
So when the user press the button it first check the duplicate username if everything is ok, then it inserts the row.
Btw the error is occur when i press on submit button and it gave me this Must declare the scalar variable "#cUserName". on adapter.Fill(haha) line.
Please i want to know what is wrong with my code. Help me
Thanks in advance.
Error message shows everything you need to know to solve that issue. You're using parameter #cUserName in your query, but it is never set.
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim command As New SqlCommand(query1, conn )
Dim param As New SqlParameter()
param.ParameterName = "#cUserName"
param.Value = username
command.Parameters.Add(param)
Using adapter = New SqlDataAdapter(command)
You are using a Parameter #cUserName but you did not initialize it or pass values to it.
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim command As New SqlCommand(query1, conn)
command.Parameters.AddWithValue("#cUserName",username)
Using adapter = New SqlDataAdapter(command)