Você está na página 1de 13

VB.

NET has a powerful set of control statements and functions that include:
CONDITIONAL If statement

Control Structures

Select statement LOOPING Do/Loop statement For statement

If/Then Statement
The simplest form of the If/Then statement in VB.NET is used to execute a statement, or set of statements, when a condition is true
The single-line versions of the If can be used for simple situations
If a < 0 Then a = 0 If employeeType = "Salaried" _ Then grossPay = 40 * payRate

However, this shortened version does not lend itself well to maintainability. The multi-line version of the If is more flexible and requires an End If statement.
If employeeType = "Salaried" Then grossPay = 40 * payRate End If If planCode <> 5 Then rate = planCode * 9.95 Console.WriteLine("Basic rate is {0}", rate) End If

The conditional expression may use any of the relational or logical operators discussed the previous chapter.
If insuranceInForce And deductiblePaid > 1000 Then fullyCovered = True coveredAmount = cost End If

If/Then/Else Statement
The If/Else statement can be used to indicate that different actions must be taken depending on whether a condition is true
' Single line version If units < 0 Then stat = "Invalid" Else stat = "OK" ' Multi-line version If employeeType = "Salaried" Then grossPay = 40 * payRate Else grossPay = hoursWorked * payRate End If

If statements may be nested to make a decision between a set of possible choices.

When statements are nested, each If statement must be considered as being unique and each requires its own End If.

If studentClassification = "undergraduate" Then tuition = creditHours * 80 Else If studentClassification = "graduate" Then tuition = creditHours * 90 Else If studentClassification = "nondegree" Then tuition = creditHours * 65 Else tuition = 0 Console.WriteLine( _ "Invalid classification!") Exit Sub ' exits the procedure End If End If End If

The If/ElseIf statement can be used in place of the nested If/Else statements.
Only one End If is required.
If classification = "undergraduate" Then tuition = creditHours * 80 ElseIf classification = "graduate" Then tuition = creditHours * 90 ElseIf classification = "nondegree" Then tuition = creditHours * 60 Else tuition = 0 Console.WriteLine("Invalid classification!") Exit Sub ' exits the procedure End If

Select Case Statement


The Select statement is used to specify an action determined by a set of values
The value of the variable determines which case is executed. Case statements may contain a single value or a list of values.
Select Case city Case "Norman", "Tulsa" state = "Oklahoma" Case "Los Angeles", "San Francisco", "Stockton" state = "California" Case "Baltimore", "Greenbelt", "St. Mary's City" state = "Maryland" Case Else state = "*Unknown*" End Select

Case statements may also contain a range of values or use a relational operator
Select Case testScore Case 100 ' single value grade = "A+" Case Is >= 92 ' Is <operator> value grade = "A" Case 90, 91 ' list of values grade = "A-" Case 88 To 89 ' range of values grade = "B+" Case Else grade = "Who cares!" End Select

Looping
There are two basic types of loops.
A pre-test loop tests the condition before the body of the loop is executed. It is possible, using a pre-test loop, that the body of the loop might never be executed. A post-test loop tests the condition after the body of the loop is executed. The number of iterations in a post-test loop is at least one.

VB.NET provides several forms of looping constructs that include both pre-test and post-test abilities.

Do/Loop Statement
The Do/Loop is the primary looping construct used in VB.NET. There are two forms of the Do/Loop.
Console.Write("Enter a number(<0 to stop): ") num = Convert.ToInt32(Console.ReadLine()) Do While num >= 0 sum += num Console.Write("Enter a number(<0 to stop): ") num = Convert.ToInt32 (Console.ReadLine()) Loop Console.WriteLine("The sum is {0}", sum)

The Do While statement is used to loop through a set of code while some condition is true.

The Do Until statement, is used to loop through a set of code until some condition is true.
Console.Write("Enter a number (<0 to stop): ") num = Convert.ToInt32(Console.ReadLine()) Do Until num < 0 sum += num Console.Write("Enter a number(<0 to stop): ") num = Convert.ToInt32 (Console.ReadLine()) Loop Console.WriteLine("The sum is {0}", sum)

There are post-test versions of the Do While and Do Until statements.


The condition is placed after the Loop keyword instead of the Do keyword.
Do Console.Write("Enter a number (<0 to stop): ") num = Convert.ToInt32(Console.ReadLine()) If num > 0 Then sum += num End If Loop While num > 0 Console.WriteLine("The sum is {0}", sum) Do Console.Write("Enter a number (<0 to stop): ") num = Convert.ToInt32(Console.ReadLine()) If num > 0 Then sum += num End If Loop Until num < 0 Console.WriteLine("The sum is {0}", sum)

Both versions are pre-test loop constructs. A pre-read (one that appears before the condition) is necessary so that, if the first number the user enters is negative, we can immediately stop the loop.

These looping examples are illustrated in two versions of the SumOfNumbers program.

Notice that we had to use an If after the ReadLine to make sure we didn't process the stop condition.

Leap Year Example


The LeapYear program calculates whether a given year is a leap year.
Any year evenly divisible by 4 is a leap year except those years that are also evenly divisible by 100. One exception: If the year is evenly divisible by 400, it is a leap year.
' Leap year calculator Module LeapYear Sub Main() Dim year As Integer Dim goAgain As String Do Console.Write("Enter a year: ") year = Convert.ToInt32(Console.ReadLine()) If year Mod 4 = 0 And (year Mod 100 <> 0 _ Or year Mod 400 = 0) Then Console.WriteLine( _ "{0} is a leap year", year) Else Console.WriteLine( _ "{0} is not a leap year", year) End If Console.Write( _ "Do you want to try another (y/n)? ") goAgain = Console.ReadLine() Loop While goAgain = "y" End Sub End Module

The output might resembles the following:


Enter a year: 1900 1900 is not a leap year Do you want to try another Enter a year: 1995 1995 is not a leap year Do you want to try another Enter a year: 1996 1996 is a leap year Do you want to try another Enter a year: 2000 2000 is a leap year Do you want to try another (y/n)? y

(y/n)? y

(y/n)? y

(y/n)? n

Exiting Do Loops Prematurely


Any Do/Loop may be exited prematurely by using the Exit Do statement.
When this statement is executed, execution is immediately transferred to the first statement following the Loop keyword. See same LeapYear example .
Do Console.Write("Enter a year: ") year = CInt(Console.ReadLine()) If year < 0 Then Console.WriteLine( _ "Invalid year... terminating!") Exit Do End If ' Calculate whether the year is a leap ' year and print the results Console.Write( _ "Do you want to try another (y/n)? ") goAgain = Console.ReadLine() Loop While goAgain = "y"

While Statement
Another version of a pre-test while loop is the While statement.
It has roots in earlier versions of VB. It has been retained for compatibility reasons. This statement functions exactly like its corresponding Do/Loop statement. The Exit While statement provides an early exit from the While.
While num >= 0 Console.Write("Enter a number(<0 to stop): ") num = Convert.ToInt32(Console.ReadLine()) If num < 0 Then Exit While sum += num End While Console.WriteLine("The sum is {0}", sum)

For/Next Statement
The For/Next statement is a looping construct that is used when the number of times that the body of the loop executes is fixed.
The statement initializes a counter variable to a starting value, specifies an ending value, and an increment If the increment value is positive, the loop executes if the counter is <= the ending value.
For year = 1776 To 2038 Step 4 Console.WriteLine("{0} is an election year", _ year) Next

If the increment is negative, the loop executes if the counter is >= the ending value.
For countdown = 10 To 1 Step -1 ... Next

If the increment is omitted, it is assumed to have the value 1.


For index = 1 To 5 ... Next

The Exit For statement to exit early from a For loop.


For i = 1 To 100 answer = Console.ReadLine() If answer = "Q" Or answer = "q" Then Exit For ' calculations go here Next

A Random Number Example

The LuckyGuess program selects a random number between 1 and 10 and gives the user three chances to guess the number.

Hints such as Too low and Too high are displayed after each guess if the user is unsuccessful. Rnd() returns a random number between 0 and 1. To scale it to a number in a specified range, you must use the following formula:
Int (lowerbound + Rnd() * upperbound)

Int() truncates the fractional part of the number.

The algorithm used by Rnd() generates pseudo-random numbers. To generate different sequences each time the program is executed, you must initialize the generator by calling the Randomize() function.
' Lucky Guess Module LuckyGuess Sub Main() Dim randomNumber As Integer Dim chance, guess As Integer ' Initialize the random number generator Randomize() ' Calculate a random number between 1 and 10 randomNumber = Int(1 + 10 * Rnd()) ' Give the user three chances For chance = 1 To 3 ' Get their guess Console.WriteLine( _ "Enter guess #{0}: ", chance) guess = _ Convert.ToInt32(Console.ReadLine()) ' Determine how accurate their guess was If guess = randomNumber Then Console.WriteLine( _ "Congratulations! You found it!") Exit For ElseIf guess < randomNumber Then Console.WriteLine("Too low!") Else Console.WriteLine("Too high!") End If Next Console.WriteLine( _ "The number was {0}", randomNumber) End Sub End Module Enter guess #1: 6 Too high! Enter guess #2: 1 Too low! Enter guess #3: 2 Too low! The number was 4

One possible set of output from running this program is shown here:

Another possible set of output from running this program could be:

Enter guess #1: 7 Too high! Enter guess #2: 3 Congratulations! You found it! The number was 3

Windows Forms
Windows Forms is that part of the .NET Framework that supports building traditional GUI applications on the Windows platform.
Windows Forms provides a large set of classes that make it easy to create sophisticated user interfaces. These classes are available to all .NET languages.

Your VB.NET Windows application will typically have a main window that is implemented by building a class derived from System.Windows.Forms.Form.
Object

Control

ScrollableControl

ContainerControl

Form

UserControl

Your Form

Building a Windows Application


The application can be designed using Visual Studio .NET, which provides a visual drag-and-drop tool known as the Windows Forms Designer.
You can also connect events to the controls using this tool. The only programming needed is the coding of the event handler.

The following demonstration describes the creation of a simple Windows application that allows the user to enter his name and then displays a basic greeting when the user presses a button.

2. It generates an initial startup form named Form1 that is stored in a file called Form1.vb that serves as your main window. It should also display the Toolbox, which contains all of the basic .NET controls that can be placed on your form. If your Toolbox is not visible, use the View menu to display it.

3. Change the name of this class and the file to MainForm and MainForm.vb, respectively. The name of the class can be changed using the Properties window by setting the Name property to MainForm. You can confirm that this changed the name of the on the Solutions class by pressing the View Code button Explorer toolbar. When the code window is displayed, you see all of the code that has been generated thus far:

Public Class MainForm Inherits System.Windows.Forms.Form ... End Class 4. You can change the name of the file in the Solutions Explorer window to MainForm.vb by right-clicking on the name of the file and choosing rename. 5. Finally, you must change the Startup Object in the projects properties from Form1 to MainForm. You may right-click on the project name in the Solutions Explorer window and choose Properties, or you may use the Project | Properties menu.

Using the Windows Forms Designer


You can use the Windows Forms Designer to design the user interface of a Windows application. The Toolbox contains a variety of controls that can be placed on a form in order to interact with a user.

Double-clicking on a controls icon in the Toolbox drawn the control on the form in a default position -- it can then be moved to any position you desire. You may also drag a control from the toolbox and drop it where you want.

6. Continuing with the demo Add the controls that are shown on the following screen snap to your MainForm and set their properties using the Properties Window accordingly. The graphic identifies the types of the controls that were drawn and the properties that were changed for each control.

Aligning Controls
The Layout toolbar can be used to align two or more controls, to make two or more controls the same size, to control the distance between two or more controls, and so on.
7. To align the controls on our GreetingDemo, - Select both the label and the text box, and chose Align Top. - With the label and the text box still selected, chose Center Horizontally. - We selected the button, and chose Center Horizontally.

Setting the Tab Order


You can set the tab order of the controls on the form using the View | Tab Order menu.
Your form must have the focus for the Tab Order option to appear on the View menu. It displays the form and places numbers representing the current tab order over each control. As you click on the controls, the tab order changes -- the first control you click on becomes number 0, the second control you click on becomes number 1, and so on. When you are finished, use the View | Tab Order menu to make the numbers go away.

8. Set the tab order on our form to that shown.

Trapping Events
In order to respond to a users actions, Windows applications must trap events.
For example, if a user clicks on a button, a program might calculate a value

When object variables are declared using WithEvents, events can be trapped and responded to.
In the case of a Windows application, all controls placed on the form have variables associated with them that are declared using WithEvents. A quick look at the code generated for our form shows:
Public Class MainForm Inherits System.Windows.Forms.Form ... Friend WithEvents lblName As _ System.Windows.Forms.Label Friend WithEvents txtName As _ System.Windows.Forms.TextBox Friend WithEvents btnClickMe As _ System.Windows.Forms.Button ... End Class

Você também pode gostar