Getting error from Isnumeric() VB.NET - 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.

Related

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.

Input Validation Using If Statements

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

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

VB.NET Have whole program loop until user decides to exit?

I have a simple program to average ten (user-defined) numbers and then print the result. At the end of the program I'd like to print Would you like to average a new set of numbers? (Y/N) If the user inputs y than I want the program to execute again from the top. If the user inputs n than the program should close. I've tried researching this, but only found ways to have the entire console exit and re-open which is not what I want.
To detect what the user has entered you have a couple options:
Console.ReadKey()
will read the next keystroke. You can then use a simple Select Case branch to choose what to do.
You can also use:
Console.ReadLine()
which will return a string (after the user presses enter). You can then use a simple If statement to determine what's in the string (and repeat the query if something other than "y" or "n" was entered.)
Example:
Shared Sub Main()
While True
AverageNums()
Console.WriteLine( "Do you want to run again? (Y/N)" )
Dim key = Console.ReadKey()
If key.Key = ConsoleKey.N Then
Exit While
End If
End While
End Sub
Shared Sub AverageNums()
' ...
End Sub
My response may be a little late in the game, but thought I'd share a compact version implementing a try-catch method.
Sub Main()
Do
Try
Console.Write("Enter a value: ")
Console.ReadLine()
'...
SomeProcedure()
Catch ex As Exception
Console.WriteLine(ex.ToString)
Finally
Console.Write("Enter another value? (N for No) ")
End Try
Loop Until Console.ReadLine() = "N"
End Sub
Sub SomeProcedure()
'...
End Sub

In Visual Basic, I keep getting String To double Error

I am trying to add a length check in my coffee shop program...
i have sorted some of it out but i cant see where I am going wrong.
Dim Name As String
MsgBox("Welcome. You Are On The 'Hot Mornings' Self-Ordering Service", vbInformation, "Welcome To Hot Mornings!")
Name = InputBox("Please Enter Your Name", "Welcome To Hot Mornings!", , MsgBoxStyle.OkCancel)
If Len(Name <= 3) Then
Do Until Len(Name > 3)
MsgBox("Error!", vbExclamation, MsgBoxStyle.OkOnly)
MsgBox("An Error Occureed Earlier. We Are Currently Trying To fix This Issue.", vbInformation, "Error!")
Name = InputBox("Please Enter Your Name.", , "Must Contain More Than 3 Characters", MsgBoxStyle.OkCancel)
Loop
End If
Len(Name <= 3)
This code doesn't make any sense.
You're checking whether Name (a string) is less or equal to than 3 (huh?), then getting the Len() of the result of that check. (huh?)
You probably want to get the Len() of the string (Len(Name)), then check whether the result of that (which is a number) is less than or equal to 3.