ISNUMERIC AND EMPTY STRING - vb.net

I want to create an application where if someone enters a number, it is entered into a listbox but if someone enters an alphabet or leave the textbox blank, a message box should appear. How to do this? Thanks.
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim grade As Double
grade = CDbl(txtGrades.Text)
If grade >= 0 And IsNumeric(grade) = True Then
lstGrades.Items.Add(grade)
txtGrades.Text = " "
ElseIf txtGrades.Text = " " Then
MessageBox.Show("Number cannot be less than 0", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf IsNumeric(txtGrades.Text) = False Then
MessageBox.Show("Number cannot be an alphabet", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub

You could simplify your logic and eliminate errors by using TryParse. This method determines if a String can be converted to a Double and returns either True or False along with the converted value:
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim grade As Double
If Double.TryParse(txtGrades.Text, grade) Then
lstGrades.Items.Add(grade)
txtGrades.Text = " "
Else
MessageBox.Show("Number cannot be an alphabet", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub

Related

Program works when I input the number but when I backspace it to enter another number it shows error

My program works when I input the number but when I backspace it to enter another number it shows an error.
Public Class Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim calculate = 100
Label1.Text = "The calculation is " & (TextBox1.Text * calculate)
End Sub
End Class
Before your calculation you have to check that TextBox1.Text <> "".
If TextBox1.Text <> "" Then
Label1.Text = "The calculation is " & (TextBox1.Text * 100)
Else
Label1.Text = "no value"
End If

Catching a [Tab] or [Enter] on KeyPress Event

Is it possible to catch the Enter or Tab key in the KeyPress Event?
I am entering a numeric only value on a comboBox, but once this value has been validated I want the user to be able to either Tab or Enter out of the CB once validated, is this possible from within the keyPress? Here's my code;
Private Sub cbCheckAmount_KeyPress(sender As Object, e As KeyPressEventArgs) Handles cbCheckAmount.KeyPress
'Only allowed characters
Dim allowedChars As String = "0123456789."
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
If e.KeyChar <> ControlChars.Back Then
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character, notify clear and return
nonNumberEntered = True 'Set to True to 'swallow' the keypress and prevent the TextChanged event from firing.
MsgBox("Numbers only", MsgBoxStyle.Exclamation)
cbCheckAmount.Text = ""
cbCheckAmount.Focus()
cbDollarAmount.Text = ""
End If
End If
End If
'If shift key was pressed, it's not a number.
If Control.ModifierKeys = Keys.Shift Then
nonNumberEntered = True
cbCheckAmount.Text = ""
cbCheckAmount.Focus()
End If
End Sub
Private Sub cbCheckAmount_TextChanged(sender As Object, e As EventArgs) Handles cbCheckAmount.TextChanged
'Call the function to create a text line out of the numbers
'Regex to ensure the string contains numbers
Dim t As ComboBox = sender
Dim foo As Decimal
If Decimal.TryParse(cbCheckAmount.Text, foo) Then
'data is good
Dim re As New Text.RegularExpressions.Regex("\d")
If re.IsMatch(cbCheckAmount.Text) Then
If nonNumberEntered = False Then
Dim newNum = cbCheckAmount.Text.Trim
'If there are any leading weird . in the string
newNum = newNum.TrimStart(".")
Dim newStr As String
'Build the array
Dim newDec As String() = newNum.Split(New Char() {"."c})
If newNum.Contains(".") Then
newStr = NumberToText(newDec(0))
cbDollarAmount.Text = newStr & " Dollars and " & newDec(1) & "/100 "
Else
newStr = NumberToText(newDec(0))
cbDollarAmount.Text = newStr & " Dollars and 00/100 "
End If
End If
End If
Else
'data is bad
nonNumberEntered = False
cbCheckAmount.Text = ""
cbCheckAmount.Focus()
cbDollarAmount.Text = ""
End If
End Sub
I'm using VB 2015
Stop and listen. The problem you're trying to solve doesn't exist. Just do it properly in the first place. Handle the Validating event of each control and do your validation there. If validation fails, set e.Cancel to True and the control will retain focus. In the Click event handler of your OK Button or whatever, call the ValidateChildren method and that will raise the Validating event on every control, even if it never received focus. If any controls fail validation, ValidateChildren returns False and you know not to try to use the data. E.g.
Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
Dim value = TextBox1.Text.Trim()
'Data is optional but must be numeric if provided.
If value <> String.Empty AndAlso Not Double.TryParse(value, Nothing) Then
TextBox1.SelectAll()
TextBox1.HideSelection = False
MessageBox.Show("If data is provided, it must be numeric", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error)
TextBox1.HideSelection = True
e.Cancel = True
End If
End Sub
Private Sub TextBox2_Validating(sender As Object, e As CancelEventArgs) Handles TextBox2.Validating
'Data is required.
If TextBox2.Text.Trim() = String.Empty Then
TextBox2.SelectAll()
TextBox2.HideSelection = False
MessageBox.Show("Data must be provided", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error)
TextBox2.HideSelection = True
e.Cancel = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ValidateChildren() Then
'The data has passed validation so it is safe to use it.
End If
End Sub
If i understand correctly isnt what you want just
If e.KeyChar = ChrW(Keys.Return) or e.KeyChar = Keys.Tab Then
''somethign something''
End If

Input Numbers and Unit Grades Only at Textbox (VB.Net)

Hi I Just Want to Input 1 to 5 only as unit grades on textbox
i use this code:
Private Sub TextBox16_TextChanged(sender As Object, e As EventArgs) Handles TextBox16.TextChanged
If TextBox16.Text >= 5 Then
TextBox16.clear()
MsgBox("Unit Grades Only From 1 to 5")
End If
End Sub
End Class
error came up:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Double' is not valid.
Alright you have two ways to do this:
Preventing Typing Them
In this case, you will deny user from typing other characters. So code this:
Private Sub TextBox16_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox16.KeyPress
'Deny user from entering more than one charecter
TextBox1.MaxLength = 1
Select Case e.KeyChar
Case "1", "2", "3", "4", "5" ,vbBack 'vbBack is backspace
'You can enter any number that you whant
e.Handled = False
Case Else
'Ignore the key
e.Handled = True
'Play a Beep sound.
Beep()
End Select
End Sub
or
Checking With TextChanged
Type in this in your method:
Dim textbox_val As Integer
'The user may enter alphabetical characters
Try
textbox_val = Convert.ToInt32(TextBox1.Text)
Catch ex As Exception
MsgBox("Unit Grades Only From 1 to 5")
Exit Sub
End Try
If textbox_val >= 5 Then
TextBox1.Clear()
MsgBox("Unit Grades Only From 1 to 5")
End If
If you have your heart set on using a textbox for this , the following code should prevent any besides a 1 through 5 in the textbox. I used a textbox with a bit better naming txtUnitGrade.
Private _sLastValidValue As String = String.Empty
Private _bIgnoreChange As Boolean = False
Private Sub txtUnitGrade_TextChanged(sender As Object, e As EventArgs) Handles txtUnitGrade.TextChanged
If Not _bIgnoreChange Then
If txtUnitGrade.Text = String.Empty Then
_sLastValidValue = String.Empty
Else
If Not IsNumeric(txtUnitGrade.Text) Then
SetValueToLast()
Else
Dim iParsedValue As Integer = Integer.MinValue
If Not (Integer.TryParse(txtUnitGrade.Text, iParsedValue)) OrElse iParsedValue < 0 OrElse iParsedValue > 5 Then
SetValueToLast()
Else
_sLastValidValue = txtUnitGrade.Text
End If
End If
End If
End If
End Sub
Private Sub SetValueToLast()
Beep() 'you could add some other audible or visual cue that an block occured
_bIgnoreChange = True
txtUnitGrade.Text = _sLastValidValue
txtUnitGrade.SelectionStart = txtUnitGrade.Text.Length
_bIgnoreChange = False
End Sub

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