Input Validation Using If Statements - vb.net

My project assignment requires the use of input validation using If statements. In addition, if the user leaves the Trade Allowance field blank, a default $0 should be used. My textbook is not helping me understand how these work at all, it will only show small sections of code, and it doesn't show any practical use. My overall project is working as intended, but when I try to input nonnumeric data, or leave a field blank the program crashes. It does show the message I set, but it doesn't give the user a chance to fix their error.
'Having a problem here...
AccessoriesTextBox.Text = AccessoriesAndFinish.ToString()
If CarSalesTextBox.Text <> " " Then
Try
CarSalesPrice = Decimal.Parse(CarSalesTextBox.Text)
Catch CarSalesException As FormatException
MessageBox.Show("Nonnumeric data entered for Car Sales Price.", "Data Entry Error",
MessageBoxButtons.OK)
CarSalesTextBox.Focus()
End Try
ElseIf CarSalesTextBox.Text <> "" Then
MessageBox.Show("Enter the Car Sales Price.", "Data Entry Error",
MessageBoxButtons.OK)
CarSalesTextBox.Focus()
End If
'Also having a problem here...
If TradeTextBox.Text <> "" Then
TradeAllowance = 0D
If TradeTextBox.Text <> " " Then
TradeAllowance = 0D
End If
End If
'Convert Trade Allowance to Decimal
TradeAllowance = Decimal.Parse(TradeTextBox.Text)

To avoid users putting non numeric data into a textbox, you could avoid textbox ;)
The NumericUpDown was meant for inputing numbers.
But if you need to or want to use a Textbox, you make use of TryParse instead of catching exceptions.
Dim value As Decimal ' to hold the numeric value we need later
If tb.Text = String.Empty Then
' either throw error and exit method or use default value
ElseIf Not Decimal.TryParse(tb.Text, value) Then
' not a decimal, inform user and exit sub
End If
' value contains something meaningfull at this point

Related

How to make conditions when inserting empty data in masked text box in vb.net

I'm try to make 3 conditions when inserting date using masked text box. The data that I'm trying to insert into the database is passport date, it is not a required data to be inserted as not all user have passport. First condition is when there are user leave the passport date empty, the null data will be save into the database. Seconds condition is when user insert date that are not true such as "29/02/2019", a msgbox will be shown. Lastly, when user insert proper date, data will be save into database.
I've already use "textbox.Text.Trim().Length = 0" syntax but the condition does not work.
Private Sub insert_Click(sender As Object, e As EventArgs) Handles insert.Click
'insert syntax
Dim insert_command As New MySqlCommand("INSERT INTO employee(StaffID, StaffName, ExpiredDate1) _
VALUES (#StaffID, #StaffName, #ExpiredDate1)", connection)
'insert staffid
If staffid.Text.Trim().Length > 0 Then
insert_command.Parameters.Add("#StaffID", MySqlDbType.VarString).Value = staffid.Text
End If
'insert staffname
If staffname.Text.Trim().Length = 0 Then
insert_command.Parameters.Add("#StaffName", MySqlDbType.VarString).Value = DBNull.Value
Else
insert_command.Parameters.Add("#StaffName", MySqlDbType.VarString).Value = staffname.Text
End If
'insert passport date
Dim dob As Date
If edate1.Text.Trim().Length = 0 Then
insert_command.Parameters.Add("#ExpiredDate1", MySqlDbType.VarString).Value = DBNull.Value
ElseIf Date.TryParse(edate1.Text, dob) Then
insert_command.Parameters.Add("#ExpiredDate1", MySqlDbType.VarString).Value = edate1.Text
Else
MessageBox.Show("Invalid passport date", "Invalid Information", MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
End If
End Sub
The error that I got is when user does leave the date masked text box null, it does not insert the null data but read the last condition. I want user able to insert null data into the database without showing the last condition msgbox.
In Visual Studio I can place a breakpoint before this line
If edate1.Text.Trim().Length = 0 Then
Then when I execute the code in Debug mode and hit the button on the form, I can hover my mouse over the .Text function to see what the textfield contains.
Because I have not entered anything yet it shows me " / /". Apparently even an empty value still has the mask, so .Length = 0 will not work.
The easiest way would be to check if the field still has that default value, but that might cause a problem if the mask were ever to change.
When I hover my mouse over the edate1 variable (while still paused on the breakpoint) I can select a dropdown that shows me all properties and methods of that variable. I notice it has a 'MaskFull' and 'MaskCompleted' which might be of use (a full list can also be seen in the .Net Docs).
Let's test it out:
If Not edate1.MaskFull Then
Debug.Print("Not full")
ElseIf Date.TryParse(edate1.Text, dob) Then
Debug.Print("Date!")
Else
Debug.Print("Not full, no date")
End If
Output
" / /" 'Not full'.
"01/01/197" 'Not full'.
"01/01/1970" 'Date!'.
"12/34/1970" 'Not full, no date'.

My conditional statement isn't working

I am in an entry level visual basic class. I am trying to test user input to see if it us numeric using the IsNumeric boolean function. Basically, if the input is not numeric, I want it to throw up a messagebox saying so, and if it IS numeric, I want it to set the numeric values as variables. Every time I enter a non-numeric value, I don't get the messagebox, instead I get an exception when it tries to convert a non-numeric string to a double using CDbl. What am I doing wrong?
If txtInches.Text = "" Or txtFeet.Text = "" Then 'Checks to ensure height fields were not left blank
'If fields were blank, throws error message up, changes textbox backgroud color to red, focuses user on error and exits sub.
MessageBox.Show("You must enter a value for both feet and inches. Don't leave these fields blank, and try again.", "Height Error", MessageBoxButtons.OK)
txtFeet.BackColor = Color.Red
txtInches.BackColor = Color.Red
txtFeet.Focus()
Exit Sub
ElseIf txtAge.Text = "" Then 'Checks to see if age field was blank
'If age field was blank, throws error message up, changes textbox backgroud color to red, focuses user on error and exits sub.
MessageBox.Show("You must enter your age. Don't leave this field blank, and try again.", "Age Error", MessageBoxButtons.OK)
txtFeet.BackColor = Color.Red
txtInches.BackColor = Color.Red
txtFeet.Focus()
Exit Sub
ElseIf Not IsNumeric(dblFeet) Then
'If feet input is not numeric, throws error message up, changes textbox background color to red, focuses user on error and exits sub.
MessageBox.Show("Feet must be a numeric value. Please try again.", "Height Error", MessageBoxButtons.OK)
txtFeet.BackColor = Color.Red
txtFeet.Focus()
Exit Sub
ElseIf Not IsNumeric(dblInches) Then 'Checks to see if height input is numeric
'If inches input is not numeric, throws error message up, changes textbox background color to red, focuses user on error and exits sub.
MessageBox.Show("Inches must be a numeric value. Please try again.", "Height Error", MessageBoxButtons.OK)
txtInches.BackColor = Color.Red
txtInches.Focus()
Exit Sub
ElseIf Not IsNumeric(dblAge) Then 'Checks to see if age input is numeric
'If age input is not numeric, throws error message up, changes textbox background color to red, focuses user on error and exits sub.
MessageBox.Show("Your age must be a number. Please try again.", "Age Error", MessageBoxButtons.OK)
txtAge.BackColor = Color.Red
txtAge.Focus()
Exit Sub
Else
dblFeet = CDbl(txtFeet.Text)
dblInches = CDbl(txtInches.Text)
dblAge = CDbl(txtAge.Text)
End If
Oh, I figured it out. I was testing the dblVariable when I should have been testing the txtVariable.text. Facepalm.
Assuming you are interested in an education, not just a grade, here is a more succinct way using NET methods:
' assumes all the values are form/class
' leval variables
Private nAge As Int32
Then for the validation:
' if it parses, then nAge will have the value
If Integer.TryParse(tbAge.Text, nAge) = False Then
MessageBox.Show("Please enter a valid integer for Age",
"Annoying MsgBox", MessageBoxButtons.OK)
Return
End If
I dint know why you are using doubles - do you really expect "5.8" feet or an input "28.7" for age?
Using Integer.TryParse you can perform just one test: it will detect/fail on empty strings as well as "I like pie"
Rather than tell them one error at a time, you could accumulate the bad elements and tell them everything that is wrong. The ErrorProvider is good for this.
One of the problems with the old VB functions is that almost everything is As Object. This allows you to do something like IsNumeric(dblAge) which will always be true. The NET methods are more strongly typed, so that you can only pass a string.

Change invalid textbox value - VB NET

I currently have 3 textboxes. Each textbox must contain a number. If any one of the three textboxes does not contain a numeric value, show an error message. For textboxes not displaying a number, (where IsNumeric returns false), I want to change its default value. How do I do this?
If Not (IsNumeric(txtpadult.Text)) Or Not (IsNumeric(txtpjunior.Text)) Or Not (IsNumeric(txtpconc.Text)) Then
MsgBox("ERROR: INVALID NUMERIC !", vbCritical, "System Message")
End if
Thanks in advance.
First, I would recommend using the new .NET methods, when possible, rather than resorting to the old VB6 style methods. So, instead of MsgBox, I would recommend using MessageBox.Show, and instead of IsNumeric, I would use Integer.TryParse, etc.
So, for instance, you could rework your code like this:
Dim invalid As TextBox = Nothing
If Not Integer.TryParse(txtpadult.Text, 0) Then
invalid = txtpadult
ElseIf Not Integer.TryParse(txtpjunior.Text, 0) Then
invalid = txtpjunior
ElseIf Not Integer.TryParse(txtpconc.Text, 0) Then
invalid = txtpconc
End If
If invalid IsNot Nothing Then
MessageBox.Show("ERROR: INVALID NUMERIC !", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
invalid.Text = "0" ' Set to default value
End If
As you can see, as it tests each text box, if it finds one that is invalid, it keeps a reference to it in the invalid variable. Then it can check to see if one was found and set it's value. Alternatively, you could create a list of text boxes which need to be checked and then loop through them, like this:
Dim textBoxes() As TextBox = {txtpadult, txtpadult, txtpconc}
Dim invalid As TextBox = Nothing
For Each i As TextBox In textBoxes
If Not Integer.TryParse(i.Text, 0) Then
invalid = i
Exit For
End If
Next
If invalid IsNot Nothing Then
MessageBox.Show("ERROR: INVALID NUMERIC !", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
invalid.Text = "0" ' Set to default value
End If
Or, if you want to be clever, you can do it in less lines of code with a LINQ extension method:
Dim textBoxes() As TextBox = {txtpadult, txtpadult, txtpconc}
Dim invalid As TextBox = textBoxes.FirstOrDefault(Function(x) Not Integer.TryParse(x.Text, 0))
If invalid IsNot Nothing Then
MessageBox.Show("ERROR: INVALID NUMERIC !", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
invalid.Text = "0" ' Set to default value
End If

Getting error from Isnumeric() VB.NET

I'm getting runtime error when I enter alphabets in the inputbox
Dim amount As String
amount = InputBox("Enter the amount of people you want to participtate", "System Message")
If amount < 0 Or Not (IsNumeric(amount)) Then
MsgBox("Please enter positive number of people", vbExclamation, "System Message")
End If
Comparing strings to numbers is pretty dangerous and blew up in your face. You can make it work but you'll have to code is carefully, ensuring that you never try to compare a string that can't be converted to a number. That requires using another operator:
If Not IsNumeric(amount) OrElse amount < 0 Then
MsgBox("Please enter positive number of people", vbExclamation, "System Message")
End If
Note the changed order and the use of OrElse, the short-circuiting version of Or. It won't evaluate the right-hand side expression if the left-hand side is already True.
The more .NET centric way to do this is by using Integer.TryParse() to convert strings to numbers.
To avoid an error, you can make it like this ..
If IsNumeric(amount) Then
If value(amount) > 0 Then
'codes here
Else
MsgBox("Please enter positive number of people", vbExclamation, "System Message")
End If
Else
MsgBox("Please enter a number of people", vbExclamation, "System Message")
End If
So I was looking at validating a textbox, first I wanted to make sure that it was not empty and make sure that it was a number. I'm by no means an expert but I'll put the code I wrote to validate the user input. I put it in a function because I had a lot of text fields that the user had to enter.
Class MainWindow
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
tb2.Text = tbCheck(tb1)
End Sub
Private Function tbCheck(ByRef tb As TextBox) As Boolean
tbCheck = tb.Text.Length > 0
Try
tbCheck = (tb.Text / 1) > 0
Catch ex As Exception
tbCheck = False
End Try
Return tbCheck
End Function
End Class
This is just the simple program I wrote to check if the code worked as I had hoped.
Hope this can help someone or at least tell me if there is something I'm missing.

VB2008 Type Cast Exception

I have a form that has a textbox (say TextBox1). This field is of string type.
On clicking on a button, I have the below code
Dim field1 As String
If (TextBox1.Text) Then field1 = TextBox1.Text Else MsgBox("TextBox1 Code can not be empty. Enter proper value!", vbCritical, "Empty TextBox1")
I built the solution and ran it. When the form is opened, I did not enter anything in TextBox1. I clicked on the button. It throws an exception as below:
InvalidCastException was unhandled
Conversion from string "" to type 'Boolean' is not valid.
Can anyone guide as to how can I handle this exception? Also, why is it trying to convert my string to a Bool anyway?
The problem is this part:
If (TextBox1.Text)
It's trying to convert TextBox1.Text to Boolean to see whether or not to go into the block. You might have meant:
If (TextBox1.Text <> "")