Simple adding windows program
Hello guys,
I was programming this simple adding numbers program and I thought about developing it more and more
The First code is :
Code:
Dim number1, number2, sum As Integer
number1 = TextBox1.Text
number2 = TextBox2.Text
sum = number1 + number2
TextBox3.Text = sum
MessageBox.Show("Thank you for using me.")
Not that text box 3 is read only !
Now I want to make the program give an error message it the input in textbox1 and textbox2 was nothing or not integer (number)
How i do that
I tried :
Code:
if TextBox1.Text = "" then
MsgBox("ERROR")
end if
but I keep getting error that it cannot convert Integer to String !
Any Ideas ??
THANKS,
Re: Simple adding windows program
That check shouldn't cause your error so I suspect your problem is that your not exiting on an error state. Post your whole code.
Re: Simple adding windows program
Parsing the value in the text box works.
vb Code:
number1 = Integer.Parse(TextBox1.Text)
Edit:
Use it like so:
vb Code:
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim number1, number2, sum As Integer
If Not TextBox1.Text = "" Then
number1 = Integer.Parse(TextBox1.Text)
number2 = TextBox2.Text
sum = number1 + number2
TextBox3.Text = sum
MessageBox.Show("Thank you for using me.")
Else
MessageBox.Show("ERROR")
End If
End Sub
End Class
Re: Simple adding windows program
You should always check the user inputs. A proper validation should be done before doing the actual operation.
It's better to use Integer.TryParse() method to "try" converting the value from the TextBoxes to an Integer value.
Here's the example:
vb Code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'~~~ Declaring the variables
Dim num1 As Integer
Dim num2 As Integer
Dim result As Integer
If Integer.TryParse(TextBox1.Text, num1) Then '~~~ we are trying to convert the value of 'TextBox1' to Integer value. If success, the value would be stored in 'num1' variable.
If Integer.TryParse(TextBox2.Text, num2) Then '~~~ Now, we are going after the second value. That is, trying to convert the value of 'TextBox2' to Integer value. If success, the value would be stored in 'num2' variable.
result = num1 + num2 '~~~ we got the two values. So, we are adding them and storing the result in the variable named 'result'
'~~~ Now displaying the result
MessageBox.Show(String.Format("{0} + {1} = {2}", num1.ToString, num2.ToString, result.ToString)) '~~~ We are going to display the result in a MessageBox. We are using String.Format() function to format the string with placeholders.
Else '~~~ if the conversion of value from "TextBox2" to Integer fails..
MessageBox.Show("Second number should be a valid integer !", "Error")
End If
Else '~~~ if the conversion of value from "TextBox1" to Integer fails..
MessageBox.Show("First number should be a valid integer !", "Error")
End If
End Sub
End Class
:wave: