Compute the Sum of Two Numbers in Visual Basic .Net

Problem:

Write a program in vb.net that will ask the user to enter two numbers and compute the sum of that numbers.

Create a GUI (graphical user interface) and a console application for this program.

Solution:

We are going to create two forms for this program; gui version and console application.

For gui we will be using windows form application and console is creating a project in a command line application.

We will be using Microsoft Visual Studio 2010.

Kindly follow the step by step tutorial.

For Windows Form Application

  1. Open your VS2010
  2. Click File then New Project
  3. Select the Visual Basic then Windows Form Application. Click OK.
  4. We will add controls to our form.
    1. 2 labels
    2. 2 textboxes
    3. 1 button
  5. The design of the form will be like the image below.
    sumoftwo1
  6. Double the Compute button and place the code below.
If TextBox1.Text = "" Or IsNumeric(TextBox1.Text) = False Then
MessageBox.Show("Please enter a numeric value.")
TextBox1.Focus()
ElseIf TextBox2.Text = "" Or IsNumeric(TextBox2.Text) = False Then
MessageBox.Show("Please enter a numeric value.")
TextBox2.Focus()
Else
Dim sum As Integer = 0
sum = Val(TextBox1.Text) + Val(TextBox2.Text)
MessageBox.Show("the sum is: " & sum)
End If

Code Explanation:

The program will validate first the input of the user, it will check if the field is not empty or the user has entered a numeric value. The program will not compute the sum unless the user has entered a numeric value on the two textboxes. The sum of two numbers will be displayed in a message box.

sumoftwo2

  1. Save and Run the project.

For Console Application

  1. Open you VS2010
  2. Click File then New Project
  3. Select Visual Basic then Console Application, Click OK.
  4. The default code that you can see is
Module Module1

Sub Main()

End Sub

End Module
  1. Paste the code below between Sub Main() and End Sub
Dim firstNum As Integer
Dim seconNum As Integer
Dim sum As Integer
Console.WriteLine("This is a console program in vb.net that computes the sum or two numbers")
Console.WriteLine("Please enter first number:")
firstNum = Console.ReadLine
Console.WriteLine("Please enter second number:")
seconNum = Console.ReadLine
sum = firstNum + seconNum
Console.WriteLine("the sum is: " & sum)
Console.ReadLine()

Code Explanation:

First is we are going to declare 3 variables; firstnum, secondnum and sum all are integer type. Next is we’re going to ask the user to enter the first variable, the program will read that user input, same goes for the second number. Lastly is the program will add the two numbers and display the result.

  1. Save and Run the project (press F5).

sumoftwo3
Download

, , ,

Post navigation