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 <> "")
Related
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.
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
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
I am using an input box. In tat am getting the number as input. When the user presses OK the program is workin. But when I press the cancel button am getting a error message
" Conversion from String "" to 'Integer' type is not valid "
If i press cancel I need the program to end.
and also i want to know how to move to other form when i press cancel in input box
Its probably a good idea to use try parse for these situations it handles more cases than empty strings for example non numeric characters characters
Dim number As Integer
Dim result As Boolean = Int32.TryParse(inputBox.Text, number)
if Not result Then
number = 0
End If
If user didn't enter anything in the input box and press cancel, it will be an empty string. Your system won't be able to convert an empty string to integer. Therefore, your program should handle this scenario with code similar to below.
If inputBox.Text = "" Then
inputValue = 0
Else
inputValue = inputBox.Text
Am using An inputbox in my form.
If i Press OK the code is fine.
When i Press cancel the Program displayin an error. Wat should i Do ?
You should look for an empty string
Dim MyString As String
MyString = InputBox("Please enter something", "Request Info", Nothing)
If (MyString Is Nothing OrElse MyString = "") Then
'User hit cancel
Else
'Read MyString
End If
Change the code that is after the InputBox to support empty strings. InputBox will return an empty string if you cancel so the reason for the error must be that your code expects the string to have a lenght > 0.
If you edit the question to show the code that calls InputBox as well as a few lines following that line, someone can probably point out the exact error.
See the documentation for a working sample:
Interaction.InputBox Method