Escolar Documentos
Profissional Documentos
Cultura Documentos
NET has a powerful set of control statements and functions that include:
CONDITIONAL If statement
Control Structures
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
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
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)
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.
(y/n)? y
(y/n)? y
(y/n)? n
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
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)
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
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.
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.
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