VB.NET button compute then summary - vb.net

I am creating a program that if I click the button5(summary) it will not show the summary report until I first click button1(compute). How do I do this?
Relevant Code:
Private Sub Button5_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button5.Click
If Not IsNumeric(TextBox6.Text) Or _
Not IsNumeric(TextBox7.Text) Or _
Not IsNumeric(TextBox8.Text) Or _
Not IsNumeric(TextBox9.Text) Then
MessageBox.Show("Invalid Input", "Warning", _
MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf 99 >= TextBox6.Text Or _
99 >= TextBox7.Text Or _
99 >= TextBox8.Text Or _
99 >= TextBox9.Text Then
MessageBox.Show("Invalid Amount", "Warning", _
MessageBoxButtons.OK, MessageBoxIcon.Warning)
Else
Form5.Show()
Me.Hide()
Form5.Label3.Text = TextBox1.Text
Form5.Label5.Text = TextBox2.Text
Form5.Label7.Text = TextBox3.Text
Form5.Label9.Text = ComboBox1.Text
Form5.Label11.Text = TextBox4.Text
Form5.Label13.Text = ComboBox2.Text
Form5.Label15.Text = Label27.Text
Form5.Label22.Text = Label14.Text
Form5.Label17.Text = Label22.Text
Form5.Label19.Text = Label25.Text
End If
End Sub

Try calling your Button1_Click() handler at the start of your Button5_Click handler:
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Button1_Click() 'Call the handler at the start of your subroutine
If Not IsNumeric(TextBox6.Text) Or Not IsNumeric(TextBox7.Text) Or Not IsNumeric(TextBox8.Text) Or Not IsNumeric(TextBox9.Text) Then
MessageBox.Show("Invalid Input", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf 99 >= TextBox6.Text Or 99 >= TextBox7.Text Or 99 >= TextBox8.Text Or 99 >= TextBox9.Text Then
MessageBox.Show("Invalid Amount", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Else
Form5.Show()
Me.Hide()
Form5.Label3.Text = TextBox1.Text
Form5.Label5.Text = TextBox2.Text
Form5.Label7.Text = TextBox3.Text
Form5.Label9.Text = ComboBox1.Text
Form5.Label11.Text = TextBox4.Text
Form5.Label13.Text = ComboBox2.Text
Form5.Label15.Text = Label27.Text
Form5.Label22.Text = Label14.Text
Form5.Label17.Text = Label22.Text
Form5.Label19.Text = Label25.Text
End If
End Sub
Assuming Button1_Click() handles the "compute" portion, this should work for you.
An easier way to write this is to write subroutines that are contextually-named and then call those routines from your click handlers.
Example:
Private Sub Compute()
'Do computations
'Use a function instead of a sub if you need to return a value.
End Sub
Private Sub Summarize()
If Not IsNumeric(TextBox6.Text) Or Not IsNumeric(TextBox7.Text) Or Not IsNumeric(TextBox8.Text) Or Not IsNumeric(TextBox9.Text) Then
MessageBox.Show("Invalid Input", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf 99 >= TextBox6.Text Or 99 >= TextBox7.Text Or 99 >= TextBox8.Text Or 99 >= TextBox9.Text Then
MessageBox.Show("Invalid Amount", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Else
Form5.Show()
Me.Hide()
Form5.Label3.Text = TextBox1.Text
Form5.Label5.Text = TextBox2.Text
Form5.Label7.Text = TextBox3.Text
Form5.Label9.Text = ComboBox1.Text
Form5.Label11.Text = TextBox4.Text
Form5.Label13.Text = ComboBox2.Text
Form5.Label15.Text = Label27.Text
Form5.Label22.Text = Label14.Text
Form5.Label17.Text = Label22.Text
Form5.Label19.Text = Label25.Text
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Compute() 'Call compute subroutine
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Compute() 'Call compute subroutine
Summarize() 'Call summarize subroutine
End Sub

Related

Debugging in vb.net?

I'm new to coding, I've been working on my project of online billing system using Visual Basic.
The complete coding has been done, but while running the code, the totalitems and totalamt is not being calculated. Can you please debug or guide me how can I resolve this issue...
It shows errors like
1.conversion of type dbnull to string is not valid
2.string or binary data would be truncated.
Public Class billing
Dim disAmount As Double
Dim getProducID As Integer
Dim getStocks As Integer
Dim validatestock As Integer
Dim getUnitPrice As Double
Dim loadqty As Double
Dim discount As Boolean
Private Sub billing_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
getTransactionID()
GenerateInvoiceNo()
fillComboproduct()
End Sub
Private Sub getTransactionID()
Try
Dim trans As New Random
Dim numbers As Integer = trans.Next(1, 1000000)
Dim digitss As String = numbers.ToString("000000")
txttrans.Text = digitss
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub GenerateInvoiceNo()
lblInvoice.Text = "INV-" & GetUniqueKey(8)
End Sub
Public Shared Function GetUniqueKey(ByVal maxSize As Integer) As String
Dim chars As Char() = New Char(61) {}
chars = "123456789".ToCharArray()
Dim data As Byte() = New Byte(0) {}
Dim crypto As New RNGCryptoServiceProvider()
crypto.GetNonZeroBytes(data)
data = New Byte(maxSize - 1) {}
crypto.GetNonZeroBytes(data)
Dim result As New StringBuilder(maxSize)
For Each b As Byte In data
result.Append(chars(b Mod (chars.Length)))
Next
Return result.ToString()
End Function
Private Sub fillComboproduct()
Dim query As String = "Select productname From product order by productname"
Dim dtproduct As DataTable = getDataTable(query)
txtproductame.DataSource = dtproduct
txtproductame.DisplayMember = "productname"
' txtproductame.ValueMember = "productID"
If txtproductame.Items.Count > 0 Then
txtproductame.SelectedIndex = 0
End If
End Sub
Private Sub clear()
txtproductID.Text = ""
txtprice.Text = ""
txtQuantity.Text = ""
txtBalance.Text = ""
txttotal.Text = ""
txtAmtPaid.Text = ""
lblSubTotal.Text = "0"
txtproductame.Text = ""
lblTotalAmount.Text = "0.00"
lblSubTotal.Text = "0.00"
lblTotalItems.Text = "0"
txtprice.Text = ""
txtQuantity.Text = "1"
txttotal.Text = "0.00"
End Sub
Private Sub addbills()
Try
Sql = "INSERT INTO bills VALUES( '" & txtproductID.Text & "', '" & txtproductame.Text & "','" & txtQuantity.Text & "', '" & txtprice.Text & "','" & txttotal.Text & "', '" & lblInvoice.Text & "', '" & Date.Today & "')"
ConnDB()
cmd = New SqlCommand(sqL, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub loadbills()
Try
Sql = "SELECT productID,productname,qty,unitprice FROM bills WHERE invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
dgw.Rows.Clear()
Do While dr.Read = True
dgw.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub totalamt()
Try
Sql = "SELECT sum(totalamt) FROM bills where invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
lblTotalAmount.Text = dr(0)
Loop
Catch ex As Exception
End Try
End Sub
Private Sub gettotalitems()
Try
Sql = "SELECT sum(qty) FROM bills where invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
lblTotalItems.Text = dr(0)
Loop
Catch ex As Exception
End Try
End Sub
Private Sub saveitems()
Try
Sql = "INSERT INTO transactionDetails VALUES('" & txttrans.Text & "','" & lblInvoice.Text & "', '" & lblTotalItems.Text & "', '" & lblTotalAmount.Text & "', '" & txtAmtPaid.Text & "','" & txtBalance.Text & "', '" & cmdpayment.Text & "', '" & Date.Today & "')"
ConnDB()
cmd = New SqlCommand(sqL, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
If i > 0 Then
MsgBox("Billing Details Successfully saved", MsgBoxStyle.Information, "Saves Billing Details")
Else
MsgBox("Failed in Saves Billing Details", MsgBoxStyle.Information, "Saves Billing Details")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub txtproductame_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtproductame.SelectedIndexChanged
Try
ConnDB()
Dim da As New SqlDataAdapter(("select * from product where productname ='" & Trim(txtproductame.Text) & "'"), conn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count > 0 Then
Me.txtprice.Text = dt.Rows(0).Item("unitprice") & ""
Me.txtproductID.Text = dt.Rows(0).Item("productID") & ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub txtQuantity_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtQuantity.TextChanged
txttotal.Text = Val(txtQuantity.Text) * Val(txtprice.Text)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
getTransactionID()
GenerateInvoiceNo()
End Sub
Private Sub BindToText()
Try
With dgw
lblSubTotal.Text = Val(.SelectedRows(0).Cells("qty").Value) * Val(.SelectedRows(0).Cells("price").Value)
.SelectedRows(0).Cells("amt").Value = lblSubTotal.Text
End With
Catch ex As Exception
End Try
End Sub
Private Sub dgw_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgw.CellClick
BindToText()
End Sub
Private Sub dgw_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgw.SelectionChanged
BindToText()
End Sub
Private Sub txtAmtPaid_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAmtPaid.KeyPress
Dim ch As Char = e.KeyChar
If Char.IsLetter(ch) Then 'Ristricting To Input Only Digits(any number)
e.Handled = True
End If
End Sub
Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQuantity.KeyPress
Dim ch As Char = e.KeyChar
If Char.IsLetter(ch) Then 'Ristricting To Input Only Digits(any number)
e.Handled = True
End If
End Sub
Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click
Try
txttotal.Text = Val(txtprice.Text) * Val(txtQuantity.Text)
If txtproductame.Text = "" Or txtQuantity.Text = "" Then
MsgBox("Please enter a product Or Quantity before you click load button")
Else
addbills()
loadbills()
totalamt()
gettotalitems()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
txttotal.Text = ""
txtQuantity.Text = ""
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
If dgw.Rows.Count = 0 Then
MsgBox("Please load drugs in the cart before saving", MsgBoxStyle.Exclamation, "Validation")
Exit Sub
End If
If txtAmtPaid.Text = "" Then
MsgBox("Please fill-in Amount Paid by Customer", MsgBoxStyle.Information, "Validation")
txtAmtPaid.Focus()
Exit Sub
ElseIf cmdpayment.Text = "" Then
MsgBox("Please choose Payment status field", MsgBoxStyle.Information, "Validation")
cmdpayment.Focus()
Exit Sub
End If
saveitems()
'DecreaseStocksOnhand()
'UpdateToDecreaseStocksOnHand()
btnreceipt.Show()
getTransactionID()
' GenerateInvoiceNo()
dgw.Rows.Clear()
' btnreceipt.Show()
End Sub
Private Sub Deleteitem()
Try
Sql = "DELETE * FROM bills WHERE productID = '" & dgw.SelectedRows(0).Cells("productID").Value & "'"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
dgw.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub btnremove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnremove.Click
If MsgBox("Are you sure you want to remove this Product from Cart", MsgBoxStyle.YesNo, "Validation") = MsgBoxResult.Yes Then
Deleteitem()
loadbills()
gettotalitems()
totalamt()
clear()
txttotal.Text = ""
txtQuantity.Text = ""
End If
End Sub
Private Sub txtAmtPaid_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmtPaid.TextChanged
txtBalance.Text = Val(lblTotalAmount.Text) - Val(txtAmtPaid.Text)
End Sub
Private Sub cmdpayment_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdpayment.SelectedIndexChanged
If cmdpayment.SelectedIndex = 1 Then
txtAmtPaid.Text = "0"
End If
End Sub
Private Sub btnreceipt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnreceipt.Click
receipt.lblInvoice.Text = lblInvoice.Text
receipt.Show()
End Sub
End Class

unhandled exception of type system.data.sqlclient.sqlexception occurred in system.dll

I been having this error
"unhandled exception of type system.data.sqlclient.sqlexception occurred in system.dll
i cant seem to find what im missing and it points on my
Private Sub Check_Info()
etc..
etc...
etc.
dDA.FILL(dDS) '<<
Notes:
I have my SQLserver running and tables running their connections are ok.
Code below
#Region " Variable Declarations "
Public sConn As SqlConnection
Dim eDS As DataSet = New DataSet
Dim eDA As SqlDataAdapter = New SqlDataAdapter
Dim eDR As DataRow
Dim dDS As DataSet = New DataSet
Dim dDA As SqlDataAdapter = New SqlDataAdapter
Dim dDR As DataRow
'Public bExitApplication As Boolean
#End Region
#Region " User-defined Procedures "
Private Sub Check_Info()
sConn.Open()
eDA.SelectCommand = New SqlCommand("SELECT emp_fname,emp_lname,emp_mname FROM tblEmployee WHERE emp_idno='" & TextBox1.Text.ToString & "' and emp_pass='" & TextBox2.Text & "'", sConn)
eDS.Clear()
eDA.Fill(eDS)
If eDS.Tables(0).Rows.Count > 0 Then
eDR = eDS.Tables(0).Rows(0)
TextBox3.Text = eDR("emp_lname") & ", " & eDR("emp_fname") & " " & eDR("emp_mname")
dDA.SelectCommand = New SqlCommand("SELECT * FROM tblDTR WHERE emp_idno='" & TextBox1.Text & "' AND date_timein=#" & Format(Now, "MM/d/yyyy") & "# AND time_timeout IS NULL", sConn)
dDS.Clear()
dDA.Fill(dDS)
If dDS.Tables(0).Rows.Count > 0 Then
dDR = dDS.Tables(0).Rows(0)
Button1.Enabled = True
Button1.Text = "&Time Out"
TextBox4.Text = Format(dDR("time_timein"), "h:mm:ss tt")
Else
Button1.Enabled = True
Button1.Text = "&Time In"
End If
dDR = Nothing
dDS.Dispose()
dDA.Dispose()
Else
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
Button1.Enabled = False
End If
eDR = Nothing
eDS.Dispose()
eDA.Dispose()
sConn.Close()
End Sub
Private Sub ReturnFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox3.GotFocus, TextBox4.GotFocus, TextBox5.GotFocus
TextBox1.Focus()
End Sub
Private Sub TextboxChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
If (TextBox1.Text <> "" And TextBox2.Text <> "") Then
Check_Info()
End If
End Sub
Private Sub LoginGotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
End Sub
#End Region
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sConn = New SqlConnection("Data Source=(localdb)\Projects;Initial Catalog=StudInfo;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False")
Label2.Text = Format(Now, "MMMM d, yyyy h:mm:ss tt")
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Label2.Text = Format(Now, "MMMM d, yyyy h:mm:ss tt")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Time-in and Time-out button
Dim strSQL As String
sConn.Open()
If Button1.Text = "&Time In" Then
dDR = dDS.Tables(0).NewRow()
TextBox4.Text = Format(Now, "h:mm:ss tt")
strSQL = "INSERT INTO tblDTR (emp_idno, date_timein, time_timein) VALUES ('" & TextBox1.Text & "', #" & Format(Now, "MM/d/yyyy") & "#, #" & TextBox4.Text & "#)"
Button1.Text = "&Time Out"
Else
TextBox5.Text = Format(Now, "h:mm:ss tt")
strSQL = "UPDATE tblDTR SET time_timeout=#" & TextBox5.Text & "# WHERE emp_idno='" & TextBox1.Text & "' AND date_timein=#" & Format(Now, "MM/d/yyyy") & "# and time_timein=#" & TextBox4.Text & "#"
Button1.Text = "&Time In"
End If
Dim dCmd As SqlCommand = New SqlCommand(strSQL, sConn)
dCmd.ExecuteNonQuery()
dCmd.Dispose()
dDR = Nothing
dDS.Dispose()
dDA.Dispose()
sConn.Close()
Button1.Enabled = False
TextBox1.Clear()
TextBox2.Clear()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' clear the form
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
Button1.Text = "&Time In"
Button1.Enabled = False
TextBox1.Focus()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
' System Administration
bExitApplication = True
Dim f As Form
f = New UserLogin
Me.Close()
f.Show()
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If Not bExitApplication Then
MsgBox("You cannot close the system this way..." & vbCrLf & vbCrLf & "Please Quit the application in the System Administration Module or by clicking Exit in the bottom of this window.", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error: No Administrative Privilage")
e.Cancel = True
End If
End Sub
Private Sub Label7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label7.Click
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
MsgBox("Thank you for using Attandance Monitoring System")
bExitApplication = True
Application.Exit()
End Sub
End Class
almost certainly comes from this:
...date_timein=#" & Format(Now, "MM/d/yyyy") & "#...
you aren't generating VB code, you are generated SQL code, so don't use a # in a string literal. The proper way is to put in a parameter:
dDA.SelectCommand = New SqlCommand("SELECT * FROM tblDTR WHERE emp_idno=#EmpID AND date_timein=#Today AND time_timeout IS NULL", sConn)
cmd.Parameters.Add("#Today",DbType.DateTime).Value = DateTime.Now
cmd.Parameters.Add("#EmpID",DbType.Int).Value = TextBox1.Text

Please complete required fields message box

I'm trying to do a "Please complete required fields" messagebox.
Tt does show up but "Account Created" also pops out just right after "Please complete required fields" appears whenever I try entering even one character in a textbox or clicking one of the two radio button.
Also instead of "Please complete required fields", "User already exists!" shows up whenever the fields are empty.
Can somebody tell me what's wrong with my codes?
Thank you....
Public Class CreateAccount
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname, #pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
conn.Open()
Dim strUsername As String = TextBox1.Text
Dim boolUsernameExists As Boolean = False
Using dbConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb")
dbConnection.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", dbConnection)
dbCommand.Parameters.AddWithValue("#uname", strUsername)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result > 0 Then
boolUsernameExists = True
End If
End Using
dbConnection.Close()
End Using
If boolUsernameExists Then
MessageBox.Show("Username already exists!")
Return
End If
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
conn.Close()
If TextBox1.Text = "" Or TextBox2.Text = "" Or RadioButton1.Checked = False Or RadioButton2.Checked = False Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Hide()
LoginUser.Show()
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
Dim KeyAscii As Short = Asc(e.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.Back '<--- this is for backspace
Case 13
e.Handled = True
SendKeys.Send("{TAB}") '<---- use to tab to next textbox or control
KeyAscii = 0
Case Is <= 32
' KeyAscii = 0
Case 48 To 57 '<--- this is for numbers
Exit Sub
Case 65 To 90 '<--- this is for Uppercase Alpha
Exit Sub
Case 97 To 122 '<--- this is for Lowercase Alpha
Exit Sub
Case Else
e.Handled = True
MessageBox.Show("You can only input letters and numbers!", "Create Account")
End Select
End Sub
Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
End Class
I agree with DavidSdot, your code is out of order.
Here is an example that might work. I say might because im not very good at vb.net. So you might need to change a few things to make it work. However, that being said, the following might do you well regarding the correct order in which it should go.
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
If ((TextBox1.Text <> "" And TextBox2.Text <> "") And (RadioButton1.Checked <> False Or RadioButton2.Checked <> False)) Then
conn.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", conn)
dbCommand.Parameters.AddWithValue("#uname", TextBox1.Text)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result = 0 Then
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname,#pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
Else
MessageBox.Show("Username already exists!")
Return
End If
End Using
Else
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
conn.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
You should really take a look at the logic of Button1_click sub, because it is really hard to understand.
You opening your database twice
you already inserted a user with username="" and password="" thats why you get user exists message when you have not enter anything
Account created successfully! is always shown after Please complete the required fields as there is no check/return/whatever when fields as missing
No idea why the DB Insert is called on every keystroke as there is no code for that in what you posted

Payroll form in visual basic

''I am getting major errors on the 'Call a function to calculate the commission line. Also if I have done anything else wrong please feel free to tell me. I believe my math is correct in the coding. Erros are commision decimal is not declared, sales is not declared, so on so forth Everythng is wrong with the commission line...
Private Sub SummaryToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SummaryToolStripMenuItem.Click
Dim TotalSalesDecimal As Decimal
Dim TotalBasePayDecimal As Decimal
Dim TotalCommissionsDecimal As Decimal
Dim TotalPayDecimal As Decimal
Dim MessageString As String
Const TempComRate As Decimal = 0.035D
Const PermComRate As Decimal = 0.05D
MessageString = "Total Sales: " & TotalSalesDecimal.ToString("c") &
Environment.NewLine & Environment.NewLine &
"Total Base Pay: " & TotalBasePayDecimal.ToString("C") &
Environment.NewLine & Environment.NewLine &
"Total Commission: " & TotalCommissionsDecimal.ToString("C") &
Environment.NewLine & Environment.NewLine &
"Total Pay: " & TotalPayDecimal.ToString("C")
MessageBox.Show(MessageString, "Summary Menu", MessageBoxButtons.OK)
End Sub
Private Sub ClearFormToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ClearFormToolStripMenuItem.Click
' Clear the stuff
nameTextBox.Clear()
salesTextBox.Clear()
hoursWorkedTextBox.Clear()
payRateTextBox.Clear()
Basepaylabel.Text = ""
commissionLabel.Text = ""
employeePayLabel.Text = ""
End Sub
Private Sub ColorToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ColorToolStripMenuItem.Click
basePayLabel.ForeColor = ColorDialog1.Color
commissionLabel.ForeColor = ColorDialog1.Color
employeePayLabel.ForeColor = ColorDialog1.Color
With ColorDialog1
.ShowDialog()
basePayLabel.ForeColor = .Color
commissionLabel.ForeColor = .Color
employeePayLabel.ForeColor = .Color
End With
End Sub
Private Sub FontToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles FontToolStripMenuItem.Click
With FontDialog1
.ShowDialog()
basePayLabel.Font = .Font
commissionLabel.Font = .Font
employeePayLabel.Font = .Font
End With
End Sub
Private Sub logoPictureBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles logoPictureBox.Click
If LogoToolStripMenuItem.Checked = True Then
logoPictureBox.Image = My.Resources.Train
Else
LogoToolStripMenuItem.Checked = False
End If
End Sub
Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
MsgBox("Program Name: Vintage Tours" + vbCrLf + "Programmer Name: Ryan Harvell")
End Sub
Private Sub basePayLabel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Private Sub CalcPayToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalcPayToolStripMenuItem.Click
' Define Local Variables
Dim DollarValueDecimal As Decimal
Dim HoursWorkedDecimal As Decimal
Dim PayRateDecimal As Decimal
Dim GoodDataBoolean = True
Dim Basepaydecimal As Decimal
Dim commissiondecimal As Decimal
Dim employeepaydecimal As Decimal
'Validate Text Fields
If nameTextBox.Text = "" Then
MessageBox.Show(" Please Enter A Name", " Data Is Missing",
MessageBoxButtons.OK, MessageBoxIcon.Error)
nameTextBox.Focus()
nameTextBox.SelectAll()
GoodDataBoolean = False
Else
'Validate Numeric Fields
Try
DollarValueDecimal = Decimal.Parse(salesTextBox.Text)
If DollarValueDecimal <= 0 Then
MessageBox.Show("Please Enter A Positive Dollar Value", "Data Is Missing",
MessageBoxButtons.OK, MessageBoxIcon.Error)
salesTextBox.Focus()
salesTextBox.SelectAll()
GoodDataBoolean = False
Else
Try
HoursWorkedDecimal = Decimal.Parse(hoursWorkedTextBox.Text)
If HoursWorkedDecimal <= 0 Then
MessageBox.Show(" Please Enter A Positive Amount Of Hours Worked ", "Data Is Missing",
MessageBoxButtons.OK, MessageBoxIcon.Error)
hoursWorkedTextBox.Focus()
hoursWorkedTextBox.SelectAll()
GoodDataBoolean = False
Else
Try
PayRateDecimal = Decimal.Parse(payRateTextBox.Text)
If PayRateDecimal <= 0 Then
MessageBox.Show(" Please Enter A Positive Pay Rate", "Data Is Missing",
MessageBoxButtons.OK, MessageBoxIcon.Error)
payRateTextBox.Focus()
payRateTextBox.SelectAll()
GoodDataBoolean = False
End If
Catch payrateerr As FormatException
MessageBox.Show("Please Enter A Numeric Payrate", "Data Is Missing",
MessageBoxButtons.OK, MessageBoxIcon.Error)
payRateTextBox.Focus()
payRateTextBox.SelectAll()
GoodDataBoolean = False
End Try
End If
Catch hoursworkederr As FormatException
MessageBox.Show(" Please Enter Numeric Amount Of Hours Worked", "Data Is Missing",
MessageBoxButtons.OK, MessageBoxIcon.Error)
hoursWorkedTextBox.Focus()
hoursWorkedTextBox.SelectAll()
GoodDataBoolean = False
End Try
End If
Catch dollarvalueerr As FormatException
MessageBox.Show("Please Enter A Numeric Dollar Amount", "Data Is Missing",
MessageBoxButtons.OK, MessageBoxIcon.Error)
salesTextBox.Focus()
salesTextBox.SelectAll()
GoodDataBoolean = False
End Try
End If
'process good data
If GoodDataBoolean = True Then
End If
'Call a function to calculate the base pay.
End Sub
Private Function calcbasepay(ByVal Hrsworked As Decimal,
ByVal PayRate As Decimal) As Decimal
If Hrsworked <= 40 Then
Return Hrsworked * PayRate
Else
Return 40 * PayRate + (Hrsworked - 40) * (PayRate / 2 + PayRate)
End If
End Function
'Call a function to calculate the commission.
Private Function calccommision(ByVal Commissionsales As Decimal) As Decimal
If commissiondecimal >= 500 Then
If permanentEmployeeRadioButton.Checked Then
Commissionsales = (sales * 0.05) + sales
Else
Commissionsales = (sales * 0.035) + sales
'Calculate the employee pay as the sum of base pay and commission.
Employeepaydecimal = Basepaydecimal + Commissiondecimal
'Accumulate the totals for the Summary box.
totalbasepaydecimal += basepaydecimal
totaLcommissiondecimal = commissiondecimal
totalpaydecimal = basepaydecimal
'display output
End If
End Function

How to count login attempts Visual Basic

I want to add a count of login attempts to my login function. When a user types a wrong username and password 3 times, the program should close down and show a message. Here is my code for the Login button in my Form1.vb:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "13Mendv" And TextBox2.Text = "Admin123" Or
TextBox1.Text = "Admin" And TextBox2.Text = "Admin123" Or
TextBox1.Text = "13PateS" And TextBox2.Text = "Staff123" Or
TextBox1.Text = "13KhetP" And TextBox2.Text = "Member123" Or
TextBox1.Text = "13PateN" And TextBox2.Text = "Scorer123" Or
TextBox1.Text = "13ChatP" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13BonnN" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13EarlJ" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13RajaA" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "1" And TextBox2.Text = "1" Or
TextBox1.Text = "13SchaJ" And TextBox2.Text = "Captain123" Then
Timer1.Start() 'Timer on Form1.vb show
ProgressBar1.Show() 'Progress bar on Form1.vb show
Label8.Show() 'Label8 on Form1.vb show
Button4.Show() 'Button4 on Form1.vb show
Else
If TextBox1.Text = "" And TextBox2.Text = "" Then
MsgBox("No Username and/or Password Found!", MsgBoxStyle.Critical, "Error") 'If statement for checking if there is any input in either username or password entry field
Else
If TextBox1.Text = "" Then
MsgBox("No Username Found!", MsgBoxStyle.Critical, "Error") 'Message box no username found
Else
If TextBox2.Text = "" Then
MsgBox("No Password Found!", MsgBoxStyle.Critical, "Error") 'Message box no password found
Else
MsgBox("Invalid Username And/Or Password!", MsgBoxStyle.Critical, "Error") 'Message box invlaid username and or password
TextBox2.Clear()
End If
End If
End If
End If
End Sub
What can I do to add a count into this code to properly notify the user of their 3 failed login attempts?
Public Class Form1
Dim attempts As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim user As String
user = TextBox1.Text
If user = "Jhayboy" Then
MsgBox("Access Granted")
Form2.Show()
Me.Hide()
ElseIf attempts = 3 Then
MsgBox("Maximum count of retries(3),And you'reach the maximum attempts!Try again later", MsgBoxStyle.Critical, "Warning")
Close()
Else
MsgBox("Username and Password is incorrect! re-enter again you currently have reached attempt " & attempts & " of 3.")
attempts = attempts + 1
TextBox1.Text = ""
TextBox1.Focus()
End If
End Sub
End Class
As several people have suggested, you could create a variable (cntAttempts) that keeps track of how many times the user tries to login, and if the count reaches 3, the program closes. Like this:
Private cntAttempts = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ... Then
Timer1.Start() 'Timer on Form1.vb show
ProgressBar1.Show() 'Progress bar on Form1.vb show
Label8.Show() 'Label8 on Form1.vb show
Button4.Show() 'Button4 on Form1.vb show
Else
cntAttempts += 1
If cntAttempts = 3 Then
MessageBox.Show("login failed")
Me.close()
End If
If TextBox1.Text = "" And TextBox2.Text = "" Then
...
Else
...
End If
End If
End Sub
HTH
I added the cnt as integer and increment it until cnt<=3 .
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Dim cnt As Integer = 0
If cnt <= 3 Then
If TextBox1.Text = "13Mendv" And TextBox2.Text = "Admin123" Or
TextBox1.Text = "Admin" And TextBox2.Text = "Admin123" Or
TextBox1.Text = "13PateS" And TextBox2.Text = "Staff123" Or
TextBox1.Text = "13KhetP" And TextBox2.Text = "Member123" Or
TextBox1.Text = "13PateN" And TextBox2.Text = "Scorer123" Or
TextBox1.Text = "13ChatP" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13BonnN" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13EarlJ" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "13RajaA" And TextBox2.Text = "Captain123" Or
TextBox1.Text = "1" And TextBox2.Text = "1" Or
TextBox1.Text = "13SchaJ" And TextBox2.Text = "Captain123" Then
Timer1.Start() 'Timer on Form1.vb show
ProgressBar1.Show() 'Progress bar on Form1.vb show
Label8.Show() 'Label8 on Form1.vb show
Button4.Show() 'Button4 on Form1.vb show
Else
cnt = cnt + 1
If TextBox1.Text = "" And TextBox2.Text = "" Then
MsgBox("No Username and/or Password Found!", MsgBoxStyle.Critical, "Error") 'If statement for checking if there is any input in either username or password entry field
Else
If TextBox1.Text = "" Then
MsgBox("No Username Found!", MsgBoxStyle.Critical, "Error") 'Message box no username found
Else
If TextBox2.Text = "" Then
MsgBox("No Password Found!", MsgBoxStyle.Critical, "Error") 'Message box no password found
Else
MsgBox("Invalid Username And/Or Password!", MsgBoxStyle.Critical, "Error") 'Message box invlaid username and or password
TextBox2.Clear()
End If
End If
End If
End If
End If
End Sub`
Dim a =0
If txtname.Text = "yourUsername" And txtpass.Text = "yourPassword" Then
Msgbox("Acces Granted")
a=0
Elseif txtname.Text <> "yourUsername" Or txtpass.Text <> "yourPassword" Then
a = MsgBox("INVALID USERNAME AND PASSWORD") + a
End if
If
a = 3 Then
End
End if
This is probably the best way to solve this issue:
If TextBox1.Text = "Username" And TextBox2.Text = "Password" Or
TextBox1.Text = "Admin" And TextBox2.Text = "Admin123" Then
MsgBox("Welcome!")
Me.Hide()
Form1.Show()
Else
If TextBox1.Text = "" And TextBox2.Text = "" Then
MsgBox("No Username and/or Password Found!", MsgBoxStyle.Critical, "Error")
Else
If TextBox1.Text = "" Then
MsgBox("No Username Found!", MsgBoxStyle.Critical, "Error")
Else
If TextBox2.Text = "" Then
MsgBox("No Password Found!", MsgBoxStyle.Critical, "Error")
Else
MsgBox("Invalid Username And/Or Password!", MsgBoxStyle.Critical, "Error")
TextBox2.Clear()
End If
End If
End If
End If
End Sub
End Class