Writing a standard calculator program in Visual Basic is a good exercise for beginner Visual Basic programmers. A basic calculator contains digits "0" through "9," a sign button, a decimal point button, a clear button, an equals button and buttons to perform addition, subtraction, multiplication and division. The CommandButton controls are placed on a form and minimal code is written for each button click event for the program. Results are displayed in a TextBox control at the top of the form.
- Skill level:
Other People Are Reading
Open your calculator Visual Basic project. The project should contain CommandButton controls for digits "0" through "9," a button for the number's sign, a decimal button, a clear button, an equals button and buttons to perform the specified mathematical operation.
Declare a variable type "Double" to hold the first value entered and the second value entered, if not already declared. Make the variable "private" to the form. Also be sure there are boolean variables declared to know what type of operation is being performed. A boolean value is either true or false.
Dim Private dFirst as Double
Dim Private dSecond as Double
Dim bAdd as Boolean
Dim bSubtract as Boolean
Store the digit clicked upon into the "dFirst" variable in the click event of the mathematical operator. Also capture which operation button was selected and set the boolean value accordingly. For example, if the "addition" button was clicked, set bAdd to" true." If the operation buttons were defined in an array, the code would look like:
Select case index
bDivision = True
bMultiply = True
bSubtract = True
bAdd = True
Store the second value entered into "bSecond" and then write an "If Statement" to perform the operation on the two digits and display the result in the "Equals" button click event code. The "If Statement" is written as "If bAdd Then txtResult.text = dFirst + dSecond
End If" where "txtResult" is the TextBox control at the top of the form.
Tips and warnings
- In the "Clear" button click event, clear the contents of the result text box and be sure to reset all boolean variables back to false.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for