Use MS Visual Basic

Shared by: HC12080720349
Categories
Tags
-
Stats
views:
8
posted:
8/7/2012
language:
pages:
29
Document Sample
scope of work template
							                  The Hong Kong Polytechnic University

                           Department of Computing



Comp 311 – Lab 1

Visual Basic .NET – Part 1
Objective
This lab exercise introduces you to the MS Visual Basic .NET. You will learn about simple design
of user interfaces, concept of event-driven programming and event handling.

Task 1:
Use MS Visual Basic .Net to develop a simple temperature converter which converts degree
Celsius to degree Fahrenheit, or vice versa.

The conversion formula is shown as follow:

C = (F - 32) * 5 / 9
   1. Configure Visual Studio .NET Integrated Development Environment (IDE) and create
      new project.




                                                                                               1
    1.1   Click the “Project" beside “Create”
          1.2 Click on Windows Forms Application and create a project name




          1.2 The VB design mode is shown as below:




                                                        2    Form Window



                                                                                 4

                                                                             Solution Explorer

            1   Toolbox




                                                                             3       Properties




    Toolbox consists of general user interface objects and you can drag and drop the objects

                                                                                                  2
     into the form window directly.
    Form Window is the working environment where objects and programs are placed. You
     can switch between design view and code view.
    Properties consists of the default values of each object, including form, button, label, etc.
    Solution Explorer allows you to view items and perform item management tasks in a
     solution or a project.

    1.3 Save project at c:\temp location and name the project to “tempconvert”




2. Form Design

2.1 In Solution Explorer window, double click the form Form1.vb and change the name to
"frmTempConvert.vb". OR

                                                                                                3
 In Solution Explorer window, click on the Form1.vb and go to the Properties window and
change the name of the form.



2.2 In Properties window, change the value of property Text to "Temperature Converter
Form”.




                                                                                          4
   3 Create the controls of the form.

Steps:
3.1 In the Toolbox window, select label control. Drag-and-drop it onto the Form window.

3.2 Adjust the size and position so that it is placed on the top portion of the form.

       In Properties window, change the AutoSize to False




3.3 In Properties window, change the value of property Text of "Label1" to "Temperature
Converter".



                                                                                          5
3.4 Change the Font value to "Arial, Bold and 14pt" OR




You can click the "+" to list all the values of font properties or press to … pop-up a font window.




                                                                                                  6
3.5 Change the TextAlign value to "MiddleCenter".




                                                    7
3.6 The setting for the heading is done.

Now, repeat 3.1 to 3.5 for two labels "Celsius" and "Fahrenheit".




   4 Create textbox for input and output.

Steps:
4.1 In the Toolbox window, select TextBox control. Drag-and-drop it onto the Form window.

4.2 Adjust the size and position so that it is placed right under the label Celsius.




                                                                                            8
4.3 Highlight the text box TextBox1 in Form window to have "TextBox1" appeared on the top
    of the Properties window.

4.4 In Properties window, change the name to "txtCelsius".




4.5 In Properties window, change the value of Text property to "".




                                                                                            9
4.6 Repeat 4.1 to 4.5 for another textbox txtFahrenheit. After complete, the form will become
like this:




   5 Create button.

Steps:
5.1 In the Toolbox window, select Button control. Drag-and-drop it onto the Form window.
5.2 Adjust the size and position so that it is placed right under the text box txtCelsius.




                                                                                                10
5.3 Highlight the button Button1 in Form widow to have "Button1" appeared on the top of the
   Properties window.

5.4 In Properties window, change the name to "btnCtoF".




5.5 In Properties window, change the value of Text property to "C to F".




                                                                                              11
5.6 Repeat 5.1 to 5.5 for another button btnFtoC. After complete, the form will become like this:




6. Add code for event handling.
The basic screen layout is finished. Now it is the time for us to add some intelligence to the
program. VB is a kind of event-driven programming language. Program logics are triggered by
events. Event examples include the movement of mouse or the focus of cursor, firing a button,
etc.
To do so, we have to associate the program codes with the desired events. In this exercise, we
would like to convert the input of degree Celsius to degree Fahrenheit when user press the button
C to F; or vice versa if button F to C is pressed.



                                                                                               12
Steps:
6.1 Double-click the button btnCtoF and the following screen is displayed.




We are going to modify the subroutine btnCtoF_Click. This subroutine will be triggered when a
click event happens on the button btnCtoF.

The subroutine starts with "Private Sub" which indicates the code is private for this form only.
The words "End Sub" indicates the ending of
the event.

6.2 Enter the following formula in the subroutine.

It should be like this:




6.3 Repeat 6.1 to 6.2 for button btnFtoC with the following formula:

C = (F - 32) * 5 / 9

7. Test program.
Now we are going to test the program.

7. Test the program

Steps:


                                                                                                   13
7.1 Press the "Start" button. And it starts to compile the program.




7.2 If no error occurs, the program Temperature Converter is launched.

7.3 Enter "28" to the field Celsius and press the button C to F. The calculated degree Fahrenheit
is then displayed.

7.4 Enter "70" to the field Fahrenheit and press the button F to C. The calculated degree Celsius
is then displayed.




8. Save program.

Steps:
8.1 Press "Save All" from the File menu to save all your work.
The source codes of the form and project are under the C:\Temp\tempconvert.
A .exe file is generated in under the \bin directory.




                                                                                               14
Visual Basic .NET – Part 2
This lab exercise introduces the following topics in MS Visual Basic .NET programming.
    Variables and assignment
    String and integer conversion
    Alert message
    Control flow
    Function and subroutine
    User input validation


Task 2:
1. Variables and assignment
1.1 Naming Variables

A variable in VB begins with a letter, followed by any combination of letters, underscore, or
digits. The length of variable name is between 1 to255. VB use keyword DIM to declare
variables.

Dim VariableName [As DataType] [= initexpr]

For example:
       Dim intCount
       Dim intPercent As Integer
       Dim intValue = 1
       Dim intLoop As Integer = 1

Or you can declare more than one variable in the same statement:

Dim intCount, intPercent As Integer
Dim intCount As Integer, DecPercent As Decimal

VB is not case-sensitive. So the variable name INTPERCENT and intPercent are referring to the
same variable. However, the convention is that the first 3 character specifies the data type and
capitalize each word in the variable name.

   Variables declaration

   Using Dim to declare the variable name, and using As to declare the data type:

   Dim variable name [As data type]

   e.g. Dim myName As String


                                                                                                15
Notes: VB is not case sensitive in variable name, i.e. there is no different between the variable
name “MYNAME” and “myName”

                  Nominal
 Data Type        storage      Value Range
                 allocation

Boolean        Depends on True or False
               implementing
               platform

Byte           1 byte          0 through 255 (unsigned)

Char           2 bytes         0 through 65535 (unsigned)

Date           8 bytes         0:00:00 (midnight) on January 1, 0001 through 11:59:59
                               PM on December 31, 9999

Decimal        16 bytes        0 through +/-79,228,162,514,264,337,593,543,950,335
                               (+/-7.9...E+28) with no decimal point;

                               0 through +/-7.9228162514264337593543950335 with
                               28 places to the right of the decimal;

                               smallest nonzero number is +/-
                               0.0000000000000000000000000001 (+/-1E-28)

Double         8 bytes         -1.79769313486231570E+308 through

                               -4.94065645841246544E-324 for negative values;

                               4.94065645841246544E-324 through
                               1.79769313486231570E+308 for positive values

Single         4 bytes         -3.4028235E+38 through -1.401298E-45 for negative
                               values;

                               1.401298E-45 through 3.4028235E+38 for positive
                               values

Integer        4 bytes         -2,147,483,648 through 2,147,483,647 (signed)

Long           8 bytes         -9,223,372,036,854,775,808 through
                               9,223,372,036,854,775,807 (9.2...E+18) (signed)

Short          2 bytes         -32,768 through 32,767 (signed)

Object         4 bytes on      Any type can be stored in a variable of type Object
               32-bit

                                                                                              16
                    platform

                    8 bytes on
                    64-bit
                    platform

    String          Depends on 0 to approximately 2 billion Unicode characters
                    implementing
                    platform



You can create a constant with the Const statement. Unlike the variables, the values of constants
cannot be changed while the program is running.

The syntax is:
Const VariableName [As DataType] = expression

Some books suggest to use "con" as the prefix for constants.

1.2 Assignment and Operation
    As shown in previous example, VB uses the equal sign "=" to assign values to variables.
    Basic operations include:

                                      VB Operator Type
   Operation                          Long way of writing the statement               Short way

   Addition                           intVar = intVar + 1                             intVar += 1

   Subtraction                        intVar = intVar - 1                             intVar - = 1

   Multiplication                     intVar = intVar * 1                             intVar *= 1

   Division                           intVar = intVar / 1                             intVar /= 1

   String concatenation               strVar = strVar & "New Text"                    Str    Var&=
                                                                                      "New Text"



1.3 Comment

Very often we need to insert comments into our program for readability. A comment starts with
single quote ('). When the computer reads a line that starts with single quote, it ignores that line.

For example:
'Declare variable intValue

                                                                                                     17
Dim intValue As Short = 1

    1.4 Underscore

If a line is too long to fit on a single line, a underscore (_) can be inserted at the end of the line
and continue your code on the next line. There must be a space in front of the underscore.
However, underscore does not work with the comments. For example:

txtOutput.Text = strName1 & "lives in Kowloon. " & strName2 & "
and " & _
"strName3 & "live in Hong Kong Island."

1.5 Message Box

You can use the built-in functon MsgBox to alert the users with a pop-up window. The syntax is:

MsgBox("Message", BoxStyle, MessageBoxTitle)
BoxStyle includes: MsgBoxStyle.Critical, MsgBox.Exclamation

Example:

MsgBox(“Hello World”)

If (txtName.Text = "") Then
MsgBox("Name is missing.", MsgBoxStyle.Critical, "Error")
End If

A small window is displayed if the name field is blank.




    2. Data type conversion

It is often the case that we have to convert values from one data type to another one. Common
example is to convert the input string into an integer.

This section introduces some functions designed for conversion between data types.
To convert a String value to numeric value, we can use Val() function.

intVar = Val(strVal)

To convert a numeric value to String value, we use Str() function.

                                                                                                         18
strVar = Str(intVar)

There are many other conversion functions. The following table shows some selected ones.


                              Data Type Conversion Functions

Function                      Description
Str                           Returns a String representation of a
                              numeric value
Val                           Returns a numeric representation of a
                              String value
CDate                         Returns a Date representation of a String
                              value
CBool                         Returns a Boolean representation of a
                              String value
CDbl                          Returns a Double representation of a
                              String value
CDec                          Returns a Decimal representation of a
                              String value
CInt                          Returns a Integer representation of a
                              String value
CLng                          Returns a Long representation of a String
                              value
CSng                          Returns a Single representation of a
                              String value
CStr                          Returns a String representation of a
                              value

There are functions used to check the data type of a variable. Three common ones are:

Function                        Description
IsNumeric                       Returns True if the input String is a
                                numeric value
IsDate                          Returns True if the input String is a
                                Date value
IsInteger                       Returns True if the input String is a
                                Integer value

In class Exercise 1:

Create a simple window-based currency converter (from HK$ to USD$ and vice versa).
The currency converter consists of some basic objects (e.g. label, button, textbox) and
event-driven programs. You have to give the appropriated name to the form, label and
text box …etc. The convert button should do the conversion when click on this button.


                                                                                           19
The program should check if no input of currency, and if the input is not numeric, display
an error message.



Part 3
Task 3:
1.1 IF statements

The syntax of a IF statement is:

If (Expression) Then
Program statements to execute if expression evaluates to True
Else
Program statements to execute if expression evaluates to False
End if

Example:
If (txtInput.Text = "M") Then
lblOutput.Text = "Male"
Else
lblOutput.Text = "Female"
End if

It is possible to evaluate more than one expression.

If (Expression1) Then
Program statements to execute if expression1 evaluates to True
ElseIf (Expression2) then
Program statements to execute if expression2 evaluates to True
Else
Program statements to execute if both expressions are False
End if

Example:
If (intQty >= 500) Then
lblOutput.Text = (decTotal * 0.1).ToString()
ElseIf (intQty >= 100) Then
lblOutput.Text = (decTotal * 0.05).ToString()
Else
lblOutput.Text = "NO DISCOUNT"
End if




                                                                                       20
1.2 Expression

                               Expression
   =                                        (1 = 1)

   >=                                       (2 >= 1)

   <=                                       (1 <= 2)

   >                                        (2 > 1)

   <                                        (1 < 2)

   AND                                      ( (1 < 2) And (1 = 1) )

   OR                                       ( (1 < 2) Or (1 = 1) )

   NOT                                      ( Not (1 < 2) )

   OR Using Select Case

   Example:

   Select Case choice
          Case “apple”
               fruitchoice =   1
          Case "orange"
               fruitchoice =   2
          Case "strawberry"
               fruitchoice =   3
          Case "watermelon"
               fruitchoice =   4
   End Select

1.3 For Loops

The syntax of a For loop is:

For LoopCounter = InitialValue To TerminatingValue
Program statements to execute
Next LoopCounter


                                                                      21
Example:
intSum = 0
For intCounter = 1 To 3
intSum += intCounter
Next intCounter

It is possible to increment by values other than 1.

For LoopCounter = InitialValue To TerminatingValue Step Amount
Program statements to execute
Next LoopCounter

Example: To sum up all odd values between 1 to 10.
intSum = 0
For intCounter = 1 To 10 Step 2
intSum += intCounter
Next intCounter
1.4 Do While Loop

Syntax:
Do While (Condition)
Program statements to execute
Loop

Example:
intSum = 0
intCounter = 1
Do While (intCounter < 11)
intSum += intCounter
intCounter += 2
Loop

1.5 Do Until Loop
Syntax:
Do Until (Condition)
Program statements to execute
Loop

Example:
intSum = 0
intCounter = 1
Do Until (intCounter > 10)
intSum += intCounter
intCounter += 2
Loop

1.6 Do While Loop version 2

                                                                 22
Syntax:
Do
Program statements to execute
Loop While (Condition)

Example:
intSum = 0
intCounter = 1
Do
intSum += intCounter
intCounter += 2
Loop While (intCounter < 11)

2. Function and subroutine
Functions and subroutines operate similarly but have one key difference. A function is used
when a value is returned to the calling routine, while a subroutine is used when a desired task is
needed, but no value is returned.

2.1 Invoking a subroutine or a function call
To invoke a subroutine:

SubroutineName(ParameterList)

Example:
OutputMin(intValue1, intValue2)
To invoke a function call:
VariableName = FunctionName(ParameterList)

Example:
strVariableName = inputName("please input your name:")
2.2 Write function and subroutine

The syntax of a function is:
Scope Function FunctionName(ParameterList) As ReturnType
Body of the function
End Function

Example:
Private Function Max(ByVal intValue1 As Integer, ByVal intValue2
As Integer) _
As Integer
If (intValue1 > intValue2) Then
Return intValue1
Else
Return intValue2
End If

                                                                                                 23
End Function

The syntax of a subroutine is:
Scope Sub SubroutineName(ParameterList)
Body of the Subroutine
End Sub

Example:
Private Sub showDiscount(ByVal intQty As Integer)
If (intQty >= 500) Then
lblOutput.Text = (decTotal * 0.1).ToString()
ElseIf (intQty >= 100) Then
lblOutput.Text = (decTotal * 0.05).ToString()
Else
lblOutput.Text = "NO DISCOUNT"
End if
End Function

The Scope of a function can be either Private or Public.
Private - usable only in the form that they are coded.
Public - visible to other forms

2.3 Pass by reference and pass by value

By default, the function and subroutine is declared as passing by value ('ByVal'). A copy of the
variable is created before a function/subroutine is called. Or you can pass the variable by
reference ('ByRef') to copy the location of the variable to the function/subroutine. You can mix
parameters of difference passing methods.

In class exercise 2:
Now we use MS Visual Basic .Net to develop a simple credit card application approval program.
It is a simplified approval program. User inputs an applicant's information - name, date of birth,
income level, and saving amount. The program will determine whether to accept or reject the
application.

There are 4 different income levels:
a. I1: HK$ 0 - 5,000
b. I2: HK$ 5,001 - 10,000
c. I3: HK$ 10,001 - 25,000
d. I4: Over HK$ 25,000
There are also 4 levels of saving amounts:
a. S1: HK$ 0 - 10,000
b. S2: HK$ 10,001 - 50,000
c. S3: HK$ 50,001 - 100,000
d. S4: Over HK$ 100,000

The approval rules for credit card application is as follows:

                                                                                                   24
1. There are 3 possible approval results: Reject, Accept, Accept with large credit amount.
2. The applicant should be in the age between 18 to 58. Otherwise, reject.
3. The approval result based on the income levels and saving amounts are listed:

Income Level                      Saving Amount           Result
I1                                -                       Reject
-                                 S1                      Reject
I4                                -                       Accept with large credit amount
-                                 S4                      Accept with large credit amount
                                  OTHER                   Accept

Create a new project
Steps:
3.1 Create a new project called "CreditApproval". Change the .vb to "frmCreditApproval".
3.2 Change the title of the form to "Credit Card Application Approval".
3.3 Create input fields for
Text box: Name of applicant (txtName), Date of birth (txtDob)
Radio button: Sex (rdoMale, rdoFemale)
Combo box: Income levels (cboIncome), Saving amount (cboSaving)
3.4 Create an output textbox for Age (txtAge)
3.5 Create 2 buttons: Check Approval (btnCheck), Exit (btnExit)
3.6 Name appropriated names to all the controls

The screen layout will look like this:




                                                                                             25
Preload the Combo box values.

Steps:
4.1 Locate the line InitializeComponent in the Class definition of the form. Add the following
code to initialize the combo boxes on the form when
the form is first created.
'Initialize the ComboBoxes
cboIncome.Items.Add(" HK$ 0 - 5,000")
cboIncome.Items.Add(" HK$ 5,001 - 10,000")
cboIncome.Items.Add(" HK$ 10,001 - 25,000")
cboIncome.Items.Add("Over HK$ 25,000")
cboIncome.SelectedIndex = 0
cboSaving.Items.Add(" HK$ 0 - 10,000")
cboSaving.Items.Add(" HK$ 10,001 - 50,000")
cboSaving.Items.Add(" HK$ 50,001 - 100,000")
cboSaving.Items.Add("Over HK$ 100,000")
cboSaving.SelectedIndex = 0

The screen layout will look like this:




                                                                                                 26
Set the Age field not editable, default value for Sex, andthe Tab seq
Step:

4.1 Change the ReadOnly property of txtAge to "True". Enabled property to "False"
4.2 Change the Checked property of rdoMale to "True".
4.3 Change the TabIndex property of txtName = 1, rboMale (2), rboFemale(3), txtDob (4),
cboIncome (5)
cboSaving (6), btnCheck (7), btnExit (8).

5 Terminate the program when user click 'Exit' button.

Steps:
5.1 Inside the sub btnExit_Click(), insert the following statement:
close()




                                                                                          27
the main program logic to the btnCheck_Click()

The program logic is triggered when the user clicks the button "Check Approval". We have to
validate the user input before we analyze the application.
User input validation include:
     Check if all fields are missing.
     Check the Date of Birth is a valid date value and calculate the age

Use Msgbox to display error message like:

If (txtName.Text = "") Then
MsgBox("Name is missing.", MsgBoxStyle.Critical, "Error")
End If

A small window is displayed if the name field is blank.




Repeat 5.1 for txtDob.
If (txtDob.Text = "") Then
MsgBox("Date of Birth is missing.", MsgBoxStyle.Critical,
"Error")
End If

5.2 Check if Date of Birth is valid date format. Modify the above statement as follows:

If (txtDob.Text = "") Then
MsgBox("Date of Birth is missing.", MsgBoxStyle.Critical,
"Error")
Else
If (txtDob.Text = "") Then
MsgBox("Date of Birth is missing.", MsgBoxStyle.Critical,
"Error")
ElseIf (Not IsDate(txtDob.Text)) Then
MsgBox("Invalid Date of Birth.", MsgBoxStyle.Critical, "Error")
End If
End If

5.3 Calculate the Age.
Create a new function to calculate the year.
Private Function CalYear(ByVal datValue As Date) As Integer
Return DateDiff(DateInterval.Year, datValue, Today())

                                                                                              28
End Function

Insert the following statement after the date field is correct.

txtAge.Text = CalYear(CDate(txtDob.Text))

5.4Get the user input of Income and Saving Amount. Modify the sub btnCheck as the follows:
               Select Case cboIncome.SelectedItem
                          Case "HK$ 0 - 5000"
                              shtIncome = 1
                          Case "HK$ 5001 - 10000"
                              shtIncome = 2
                          Case "HK$ 10001 - 25000"
                              shtIncome = 3
                          Case "Over HK$ 25000"
                              shtIncome = 4
                    End Select
                    Select Case cboSaving.SelectedItem
                          Case "HK$ 0 - 10000"
                              shtSave = 1
                          Case "HK$ 25001 - 50000"
                              shtSave = 2
                          Case "HK$ 50001 - 100000"
                              shtSave = 3
                          Case "Over HK$ 1000000"
                              shtSave = 4
                    End Select

5.5 Add the approval rule according to the follow:

Income Level                     Saving Amount               Result
I1                               -                           Reject
-                                S1                          Reject
I4                               -                           Accept with large credit amount
-                                S4                          Accept with large credit amount
                                 OTHER                       Accept
And check the age criteria as well as mention above.

Save and test the program.


                                     **** End of the Lab1 ****



                                                                                               29

						
Related docs
Other docs by HC12080720349
APPLICATION FORM
Views: 3  |  Downloads: 0
Out of Our Minds Banners
Views: 1  |  Downloads: 0
Sunday, 27 June, 1999 - Download as DOC
Views: 1  |  Downloads: 0
Toni MM aita, MS MFT
Views: 2  |  Downloads: 0
holy spirit conversation in
Views: 1  |  Downloads: 0
module 2 examview lessons 17 23
Views: 323  |  Downloads: 0
PLAYER PROFILE
Views: 35  |  Downloads: 0
Nerve Damage and Degeneration
Views: 12  |  Downloads: 0
Name _____ Earth # _____ Date Due
Views: 0  |  Downloads: 0
THE CELTA CRISIS Or BUSTING THE BOX
Views: 5  |  Downloads: 0