In Visual Basic, I keep getting String To double Error - vb.net

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.

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

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.

VB.NET Search Text File for Customer Number and display entire customer record in listbox

I am new to Visual Basic 2010 and have been banging my head against the wall with this one.
I have a form that accepts user input and saves it to a text file in the following format:
"Customer #:" 00
Doe, John
10350 Some Street
City, State Zip Code
Telephone Number
"Account Balance: $" 00.00
"Date Of Last Payment:" Month/Day/Year
I have a text box where the user inputs either a customer number or last name depending upon which check box is checked. The purpose of this is to search the text file for a customer record by last name or customer number.
When Searched I would like the customer with the last name or customer number
used in the search displayed in a listbox.
Here is the code I have below:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
'Local Variables
Dim ReadCustomerRecords As StreamReader
Dim strCustomerNumber As String
' Validate Search Criteria
If chkCustomerNumber.Checked = False And chkLastName.Checked = False Then
MessageBox.Show("Please select either Customer Number OR Last Name" & vbNewLine & "to narrow your search.", "Attention")
End If
If chkCustomerNumber.Checked And chkLastName.Checked Then
MessageBox.Show("You may only search by Customer Number OR Last Name." & vbNewLine & "Please revise your search.", "Attention")
End If
If chkCustomerNumber.Checked Then
ReadCustomerRecords = File.OpenText(strCustomerRecordsFile)
strCustomerNumber = ReadCustomerRecords.ReadLine()
Do Until strCustomerRecordsFile.Contains(txtSearchFile.Text)
If strCustomerNumber.Contains(txtSearchFile.Text) Then
lstCustomerSearch.Items.Add(strCustomerNumber)
lstCustomerSearch.Items.Add(ReadCustomerRecords.ReadLine())
lstCustomerSearch.Items.Add(ReadCustomerRecords.ReadLine())
lstCustomerSearch.Items.Add(ReadCustomerRecords.ReadLine())
lstCustomerSearch.Items.Add(ReadCustomerRecords.ReadLine())
lstCustomerSearch.Items.Add(ReadCustomerRecords.ReadLine())
lstCustomerSearch.Items.Add(ReadCustomerRecords.ReadLine())
Else
MessageBox.Show("The customer number you entered is not valid." & vbNewLine & "Please try again or search by Last Name.", "Attention")
End If
Return
Loop
ReadCustomerRecords.Close()
End If
If chkLastName.Checked Then
ReadCustomerRecords = File.OpenText(strCustomerRecordsFile)
End If
End Sub
The condition in this:
Do Until strCustomerRecordsFile.Contains(txtSearchFile.Text)
Is likely causing your loop not to terminate properly as it means until the name of the file contains the search term, do the code which is inside the loop. Since the name of the file never changes, your loop is likely not terminating properly.
With regards to searching the text file, you could do something instead like:
If chkCustomerNumber.Checked Then
Dim custRecords() as String = File.ReadAllLines(strCustomerRecordsFile)
Dim isRecordFound as Boolean = false
For i As Integer = 0 To custRecords.Length - 1
If custRec(i).Contains(txtSearchFile.Text) Then
isRecordFound = true;
lstCustomerSearch.Items.Add(custRec(i))
lstCustomerSearch.Items.Add(custRec(i + 1))
lstCustomerSearch.Items.Add(custRec(i + 2))
lstCustomerSearch.Items.Add(custRec(i + 3))
lstCustomerSearch.Items.Add(custRec(i + 4))
lstCustomerSearch.Items.Add(custRec(i + 5))
lstCustomerSearch.Items.Add(custRec(i + 6))
Exit For
End If
Next
If Not isRecordFound Then
MessageBox.Show("The customer number you entered is not valid." & vbNewLine & "Please try again or search by Last Name.", "Attention")
End If
End If
So it's a little different but:
We use File.ReadAllLines to read all the lines in your text file into an array of strings (each array element is one line). You could still use StreamReader like you are doing, but for simplicity the example uses File.ReadAllLines
Once we have the contents of your file, we can loop through and find the relevant customer ID (see below for a comment about this)
Once we have found the customer ID we replicate what you were doing with reading the next lines via the StreamReader with looking at the next elements in the array (noting that each array element is a file line)...A defensiveness check for you to implement here would be that we are trying to "look ahead" in the array by a number of elements but if there aren't that many elements left in the array you'll get an exception about the index being out of bounds
We can Exit For from the loop after a record has been found because it's a bit pointless to proceed any further
PS. For your file format an alternative for you to consider is to have an entire record on one line and delimited (e.g. you could use a "|" or something like that to separate records) instead of on multiple lines.
PPS. Be careful with using the Contains clause for searching because "02" would also match an address like "1002 Fake Street" instead of an ID you are looking for so you might dredge up false positives. Tweaking your file format should help you get around this.