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
- Open your VS2010
- Click File then New Project
- Select the Visual Basic then Windows Form Application. Click OK.
- We will add controls to our form.
- 2 labels
- 2 textboxes
- 1 button
- The design of the form will be like the image below.
- 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.
- Save and Run the project.
For Console Application
- Open you VS2010
- Click File then New Project
- Select Visual Basic then Console Application, Click OK.
- The default code that you can see is
Module Module1
Sub Main()
End Sub
End Module
- 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.
- Save and Run the project (press F5).