VB - Code Examples

advertisement
Code that uses comments
'*
'*
'*
'*
'*
======================================
Date:
11/30/01
Author: Anne Prince
Purpose: Calculate invoice total
======================================
'*declaration statements
Dim decOrderTotal As Decimal
Dim decDiscountPct As Decimal
Dim decDiscountAmount As Decimal
Dim decInvoiceTotal As Decimal
‘*get input Order Total
decOrderTotal = txtOrderTotal.Text
'*calculate the proper discount
If decOrderTotal >= 100 Then
decDiscountPct = 0.25
Else
decDiscountPct = 0
End If
Typical variable declarations
Dim strErrorMessage As String
Dim intIndex As Integer = 1
Dim lngMonth As Long, decRate As Decimal
Dim intStatus, intRunningValue As Integer
Dim blnAddMode As Boolean = True
Typical assignment statements
iMonth = 1
iMonth = iMonth + 1
dDiscountAmount = dOrderTotal * .2
dInvoicetotal = dOrderTotal + dDiscountAmount
dChangePercent = (dThisYTDSales – dLastYTDSales) / dLastYTDSales * 100
dArea = (dRadius ^ 2) * 3.1416
Examples of arithmetic expressions
iVarX
iVarY
dVarA
dVarB
=
=
=
=
iResult
iResult
dResult
dResult
iResult
iResult
14
8
8.5
3.4
=
=
=
=
=
=
'assume
'assume
'assume
'assume
for
for
for
for
all
all
all
all
iVarX \ iVarY
iVarX mod iVarY
dVarA / dVarB
dVarA mod dVarB
-iVarY
-iVarY + iVarX
examples
examples
examples
examples
'result
'result
'result
'result
'result
'result
=
=
=
=
=
=
1
6
2.5
1.7
-8
6
Conditional expressions
sSwitch <> "Yes"
bNewCustomer = True
bNewCustomer
dThisYTD > dLastYTD
iValue = 1
iValue Not > 99
dMonthlyInvestment > 0 And fInterestRate > 0 And iMonths > 0
(dThisYTD > dLastYTD) Or (dLastYTD <= 0 And dThisYTD >= 1000)
Statements that assign True/False values
bDiscountRate1 = dOrderTotal >= 200
bSalesIncrease = dThisYTD > dLastYTD
How to concatenate character strings
sFirstName = "Bob"
sLastName = "Smith"
sFullName = sFirstName & " " & sLastName
How to append one string to another string
sFirstName = "Bob"
sLastName = "Smith"
sName = sFirstName & " "
sName = sName & sLastName
How to append with the &= operator
sFirstName = "Bob"
sLastName = "Smith"
sName = sFirstName & " "
sName &= sLastName
Sample code using a Sub Procedure (no argument/parameter)
Private Sub btnGo_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnGo.Click
' This procedure calls the DisplayMessage procedure.
lstOutput.Items.Add("Hello from btnGo_Click procedure.")
lstOutput.Items.Add("Calling the DisplayMessage " & "procedure.")
DisplayMessage()
‘calls Display Message
lstOutput.Items.Add("Now I am back in the btnGo_Click procedure.")
End Sub
Sub DisplayMessage()
'A Sub procedure that displays a message.
lstOutput.Items.Add("")
lstOutput.Items.Add("Hello from DisplayMessage.")
lstOutput.Items.Add("")
End Sub
Sub Procedure Call and Sub Procedure Code (1 argument/parameter)
DisplayValue(5)
‘calls DisplayValue procedure
Sub DisplayValue(ByVal number As Integer)
' This procedure displays a value in a message box.
MessageBox.Show(number.ToString)
End Sub
Sub Procedure Call and Sub Procedure Code (multi argument/parameter)
ShowSum(5, 10)
‘calls ShowSum procedure
Sub ShowSum(ByVal num1 As Integer, ByVal num2 As Integer)
' This procedure accepts two arguments, and prints their sum on the form.
Dim sum As Integer
sum = num1 + num2
MessageBox.Show("The sum is " & sum.ToString)
End Sub
Numeric Funtion Call and Function Code
total = Sum(value1, value2)
Function Sum(ByVal num1 As Single, ByVal num2 As Single) As Single
Dim result As Single
result = num1 + num2
Return result
End Function
String Funtion Call and Function Code
MsgBox(“Hello “ & FullName(strFName, strLName)
Function FullName(ByVal first As String, ByVal last As String) As String
Dim name As String
name = last & ", " & first
Return name
End Function
Boolean Funtion Call and Function Code
If IsValid(intInput) = False Then
MsgBox(“Invalid Input”)
EndIf
Function IsValid(num As Integer) As Boolean
Dim status As Boolean
If num >= 0 And num <= 100 Then
status = True
Else
status = False
End If
Return status
End Function
An Event procedure that calls Sub and Function procedures
Private Sub btnCalculate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim iMonths As Integer
Dim dInterestRate, dMonthlyInvestment As Decimal
Dim bValidNumericEntries As Boolean
Me.ValidateNumericEntries(txtMonthlyInvestment.Text, txtYears.Text, _
txtInterestRate.Text, bValidNumericEntries)
If bValidNumericEntries Then
iMonths = txtYears.Text * 12
dInterestRate = txtInterestRate.Text / 12 / 100
dMonthlyInvestment = txtMonthlyInvestment.Text
lblFutureValue.Text = FormatCurrency(FutureValue(iMonths, _
dInterestRate, dMonthlyInvestment))
txtMonthlyInvestment.Focus()
Else
MessageBox.Show("Invalid data. Please check all entries.", "Error")
txtMonthlyInvestment.Focus()
End If
End Sub
Private Sub ValidateNumericEntries(ByVal Value1 As String, _
ByVal Value2 As String, ByVal Value3 As String, _
ByRef ValidEntries As Boolean)
If IsNumeric(Value1) And IsNumeric(Value2) And IsNumeric(Value3) Then
If Value1 > 0 And Value2 > 0 And Value3 > 0 Then
ValidEntries = True
End If
End If
End Sub
Private Function FutureValue(ByVal Months As Integer, _
ByVal InterestRate As Decimal, _
ByVal MonthlyInvestment As Decimal) As Decimal
Dim iIndex As Integer, dFutureValue As Decimal
For iIndex = 1 To Months
dFutureValue = (dFutureValue + MonthlyInvestment) _
* (1 + InterestRate)
Next iIndex
Return dFutureValue
End Function
Statements that use intrinsic functions
dValue = Val(sValue)
Msgbox(“Your number is:
“ & Int(10 * Rnd) + 1 )
iNameLength = Len(sFirstName) + Len(sLastName)
A statement that uses the IsNumeric function
If IsNumeric(txtOrderTotal.Text) Then
dOrderTotal = txtOrderTotal.Text
Else
MessageBox.Show("You must enter a numeric value.", "Entry error")
End If
Statements that use the formatting functions
lblDiscountAmount.Text = FormatNumber(dDiscountAmount, 2)
lblInvoiceTotal.Text = FormatNumber(dInvoiceTotal)
lblInvoiceTotal.Text = FormatCurrency(dInvoiceTotal)
lblDiscountPct.Text = FormatPercent(dDiscountPct)
An If…Then statement without an Else clause
If txtMonthlyInvestment.Text <= 0 Then
bValidData = False
End If
A simple If…Then…Else statement
If dOrderTotal >= 100 Then
dDiscountPct = 0.2
Else
dDiscountPct = 0
End If
An If statement with ElseIf clauses
If iQuantity = 1 Or
dDiscount = 0
ElseIf iQuantity >=
dDiscount = 0.1
ElseIf iQuantity >=
dDiscount = 0.2
ElseIf iQuantity >=
dDiscount = 0.3
Else
dDiscount = 0
End If
iQuantity = 2 Then
3 And iQuantity <= 9 Then
10 And iQuantity <=24 Then
25 Then
Nested If statements
If sType = "Retail" Then
If iQuantity <= 2 Then
dDiscount = 0
ElseIf iQuantity <= 9 Then
dDiscount = .1
ElseIf iQuantity <= 24 Then
dDiscount = .2
ElseIf iQuantity >= 25 Then
dDDiscount = .3
End If
Else '*(sType <> "Retail")
dDiscount = .4
End If
A Select Case statement
Select Case iQuantity
Case 1, 2
dDiscount = 0
Case 3 To 9
dDiscount = 0.1
Case 10 To 24
dDiscount = 0.2
Case Is >= 25
dDiscount = 0.3
Case Else '(< 1)
dDiscount = 0
End Select
Invoice Total Application
Form:
Control Names:
Object type
TextBox
Label
Label
Name
txtOrderTotal
lblDiscountAmount
lblInvoiceTotal
The code for the Click event of the Calculate button:
Private Sub btnCalculate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim
Dim
Dim
Dim
dOrderTotal As Decimal
dDiscountPct As Decimal
dDiscountAmount As Decimal
dInvoiceTotal As Decimal
dOrderTotal = txtOrderTotal.Text
If dOrderTotal >= 100 Then
dDiscountPct = .2
Else
dDiscountPct = 0
End If
dDiscountAmount = dOrderTotal * dDiscountPct
dInvoiceTotal = dOrderTotal - dDiscountAmount
lblDiscountAmount.Text = dDiscountAmount
lblInvoiceTotal.Text = dInvoiceTotal
txtOrderTotal.Focus
End Sub
Enhanced code for the Invoice Total application
Private Sub btnCalculate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)Handles btnCalculate.Click
Const dMinOrderTotal As Decimal = 10
Const dMaxOrderTotal As Decimal = 10000
Dim dOrderTotal As Decimal
Dim dDiscountPct As Decimal
Dim dDiscountAmount As Decimal
Dim dInvoiceTotal As Decimal
If IsNumeric(txtOrderTotal.Text) Then
If txtOrderTotal.Text > dMinOrderTotal And _
txtOrderTotal.Text < dMaxOrderTotal Then
dOrderTotal = txtOrderTotal.Text
dOrderTotal = Math.Round(dOrderTotal, 2)
If dOrderTotal >= 500 Then
dDiscountPct = 0.2
ElseIf dOrderTotal >= 250 Then
dDiscountPct = 0.15
ElseIf dOrderTotal >= 100 Then
dDiscountPct = 0.1
Else ' < 100
dDiscountPct = 0
End If
dDiscountAmount = dOrderTotal * dDiscountPct
dInvoiceTotal = dOrderTotal - dDiscountAmount
lblDiscountAmount.Text = FormatNumber(dDiscountAmount)
lblInvoiceTotal.Text = FormatNumber(dInvoiceTotal)
Else ' Out of range
MessageBox.Show("Order total must be between " & _
dMinOrderTotal & " and " & _
dMaxOrderTotal & ".", "Entry error")
End If
Else ' Not IsNumeric
MessageBox.Show("You must enter a numeric value.", "Entry error")
End If
txtOrderTotal.Focus()
End Sub
A loop that displays the numbers 0 through 4
Dim iIndex As Integer
For iIndex = 0 To 4
MessageBox.Show(iIndex)
Next
A loop that adds the numbers 2, 4, 6, 8, 10, and 12
Dim iSum As Integer
Dim iIndex As Integer
For iIndex = 2 To 12 Step 2
iSum += iIndex
Next iIndex
A loop that adds the squares of 25, 15, 5, -5, -15
Dim
Dim
Dim
For
iSquared As Integer
iSumofSquares As Integer
iIndex As Integer
iIndex = 25 To -15 Step –10
iSquared = iIndex ^ 2
iSumofSquares += iSquared
Next iIndex
A loop that calculates a future value
Dim
Dim
Dim
Dim
Dim
For
dMonthlyInvestment As Decimal
dMonthlyInterestRate As Decimal
iMonths As Integer
dFutureValue As Decimal
iIndex As Integer
iIndex = 1 To iMonths
dFutureValue = (dFutureValue + dMonthlyInvestment)_
* (1 + dMonthlyInterestRate)
Next iIndex
A Do While loop (pretest form)
Dim dMonthlyInvestment As Decimal
Dim dMonthlyInterestRate As Decimal
Dim iMonths As Integer
Dim dFutureValue As Decimal
Dim iIndex As Integer = 1
Do While iIndex <= iMonths
dFutureValue = (dFutureValue + dMonthlyInvestment) _
* (1 + dMonthlyInterestRate)
iIndex += 1
Loop
A Do Until loop (posttest form)
Dim
Dim
Dim
Dim
Dim
Do
dMonthlyInvestment As Decimal
dMonthlyInterestRate As Decimal
iMonths As Integer
dFutureValue As Decimal
iIndex As Integer = 1
dFutureValue = (dFutureValue + dMonthlyInvestment) _
* (1 + dMonthlyInterestRate)
iIndex += 1
Loop Untl iIndex > iMonths
The Future Value application
Form:
Control Names:
Object type
Label 5
Text1
Text2
Text3
Button1
Button2
TextBox
Label
Label
Name
Name lblFutureValue
txtMonthlyInvestment
txtInterestRate
txtYears
btnCalculate
btnExit
txtOrderTotal
lblDiscountAmount
lblInvoiceTotal
Code for the Future Value application:
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub btnCalculate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)Handles btnCalculate.Click
Dim
Dim
Dim
Dim
iMonths As Integer
dInterestRate As Decimal
dFutureValue As Decimal
iIndex As Integer
iMonths = txtYears.Text * 12
dInterestRate = txtInterestRate.Text / 12 / 100
For iIndex = 1 To iMonths
dFutureValue = _
(dFutureValue + txtMonthlyInvestment.Text) _
* (1 + dInterestRate)
Next iIndex
lblFutureValue.Text = FormatCurrency(dFutureValue)
txtMonthlyInvestment.Focus()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Download