VB.Net Tutorial 9: Code For Calculator

by -

In tutorial 8, we were facing a difficulty about entering two digit number in a textbox. So here is a solution; put following line of code in programming box for button 9. We have already put code for button 9 which you have to modify as shown below.

Textbox1.text = Textbox1.text & btn_Nine.text

Modify code for all the buttons in similar fashion and run the program. Make sure you put button name properly while modifying code for that respective button. Now you must be able to put two digit number in calculator as shown below:

Next part is to perform mathematical functions like addition. For that purpose, we have to define to integer variables to make VB store values put into textbox. If we define those variables inside “Private_Sub” section of button, it will be accessible only for that particular button. Hence we will define them as public, but how to do it? Go into coding section of your project and define two variables as integers. Let two variables be sum1 and sum2. Here is how to code if you have forgotten how to define variables:

Public Class Form1
Dim Sum1 As Integer
Dim Sum2 As Integer

Now that we have defined public variables,let us code for Add button. Double click on the addition button to open code window and put the following code in the section:

Sum1 = Sum1 + Val(TextBox1.Text)

In this code, we are using a new function Val() and passing attribute as “TextBox1.Text” to it. This val function will now convert whatever is in Text property of textbox into an integer. It is important as addition operation can only be performed with the numbers and content in textbox is in String format. Thus, Val() function is used to convert datatype from String to Integer.

Now that we have added two variables, we must show them to user in textbox. It can be done with the help of equal button. Here is the code for equal button:

Sum2 = Sum1 + Val(TextBox1.Text)
TextBox1.Text = Sum2
Sum1 = 0

Here, we have utilized Sum2 variable to store value of addition of whatever is there in Sum1 plus whatever user enters in textbox as second variable to be added. This addition is transferred to textbox via Sum2 variable in second line of code. And in third line we clear up Sum1 variable so that new values can be stored in it in case of iterative addition.

To see if our code is working properly run the program and try to add two numbers. If your project is giving any error, try to check if there are any mistakes in the code. Similarly we can code for other mathematical buttons in our calculator. For any queries you can comment below. Happy Coding!

  • Mosesrait

    wat i need is the code for division multiplication and subtraction ^_^

  • renan

    hello i try ur code and its effective. can you please add tha button / and * operation