vb.net decisions. the if … then statement if condition then statements end if if condition then...
Post on 21-Dec-2015
224 views
TRANSCRIPT
VB.Net Decisions
The If … Then Statement• If condition Then
Statements
• End If• If condition Then
StatementsElse
Statements
• End If• Condition:
– Simple condition:• Comparison of two expressions formed with relational operators:>, <,
=, < >, >=, <=• Boolean variable
– Complex condition:• Formed with logical operators: ( ), Not, And, Or
Complex Condition
• If 12<=Age<=65 Then Fee = 20, else Fee = 5• Admission rules: Applicants will be admitted if
meet one of the following conditions:– GPA>3.0– GPA>2.5 AND SAT >700
• Scholarship rules: Meet all the conditions:– GPA>3.2– Must be Accounting or CIS
• Admission rules: Applicants will be admitted if meet all the following conditions:– SAT>700 Or Income > 40000– Not GPA < 2.5
Order of Evaluation
• ( ), Not, And, Or
• Example: A=5, B=10, C=20, D=30– A>B OR C<B+20 AND Not(A<0 And D>10)– A>B XOR C<B+20 AND D>10 OR B>A+C
Using Boolean Variables as Flags
• A flag is a Boolean variable that signals when some condition exists in the program.
Dim goodStudent as Boolean=TrueIf daysAbsent > 10 Then
goodStudent = False
End ifIf goodStudent Then
TextBox1.text=“Good Student”
ElsetextBox1.text=“Not good student”
End If
IF … ELSEIF Statement
• IF condition THEN
statements
[ELSEIF condition-n THEN
[elseifstatements]
[ELSE
[elsestatements]]]
End If
Select Case Structure
• SELECT CASE testexpression
[CASE expressionlist-n
[Statements]
[CASE ELSE
[elsestatements]
END SELECT
Select Case Example• SELECT CASE temperature
CASE <40
TextBox1.text=“cold”
CASE < 60
Text Box1.text=“cool”
CASE 60 to 80
TextBox1.text=“warm”
CASE ELSE
TextBox1.text=“Hot”
End Select
The Expression list can contain multiple expressions, separated by commas.
Select Case number
Case 1, 3, 5, 7, 9
textBox1.text=“Odd number”
Case 2, 4, 6, 8, 10
textBox1.text=“Even number”
Case Else
End Select
Nested If
• Decision tree:
• Example: Tuition rules based on student’s status and number of units:– Undergraduate student– Graduate student
Windows Controls
• Form
• InputBox, MessageBox
• Text Box, Radio Button, Check Box, GroupBox, etc.
Form
• Methods:– Me.show(), Me.Hide, Me.Close
• Events:– Load, Activated, Closing, Closed
• Modeless form: Other forms can receive input focus while this form remains active.
• Modal form: No other form can receive focus while this form remains active.– Formname.ShowDialog()
Multiple FormsTwo forms: Form1, Form2
To Open Form2 from Form1:
Dim f2 As New Form2()
f2.Show()
Open Form2 as a Modal form:
f2.ShowDialog()
Note: Form is defined as a class. Must create an instance of the form class by using the keyword New to access the form.
Demo: Problem with the Show method.
SharingVariables Among Forms
• Define these variables with class-level scope using the Public keyword.– Must use formName to qualify variables.– – Dim f2 As New Form2()– TextBox1.Text = f2.g2 *** g2 is declared in form2
• Better way: Define these variables with project-level scope in a module using the Public keyword:– Module Module1– Public testVar As Integer– End Module
– Note: Use Project/Add Windows form to add a module.
Modules
• A file contains code such as:– Variable declarations– Procedures and functions
• Variables and procedures used by more than one form should store in a module.
• Global variables: Public
Starting Application with Sub Main
• The Sub Main procedure must reside in a module.
• Choose Sub Main as startup object. The code in Main will execute.– Write code in Main to open forms.
Sub Main ExamplePublic Sub main()
Dim myDay As Date
myDay = Today
If myDay.DayOfWeek = DayOfWeek.Saturday Or myDay.DayOfWeek = DayOfWeek.Sunday Then
Dim frmWeekEnd As New Form2()
frmWeekEnd.ShowDialog()
Else
Dim frmWeekDay As New Form1()
frmWeekDay.ShowDialog()
End If
End Sub
MsgBox
• MsgBox(prompt, other arguments)• MsgBox can return a value representing the user’s
choice of buttons displayed by the box. The return value has MsgBoxResult data type:– Dim RETurnVal As MsgBoxResult– RETuranVal = MsgBox("customer click cancel",
MsgBoxStyle.AbortRetryIgnore) If RETurnVal = MsgBoxResult.Abort Then
– MsgBox("YOU CLICK ABORT")– End If
MessageBoxMessageBox.Show(message)
MessageBox.Show(message, Caption)
MessageBox.Show(message, Caption, Buttons)
Note:
1. In each format, arguments are positional and required.
2. This object returns a DialogResult data type. To test the return value:
Dim ReturnVal as DialogResult
ReturnVal=MessageBox(“hello”, …..)
If ReturnVal=DialogResult.OK…
Form Closing Event Example
Private Sub Form2_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If MessageBox.Show("Are you sure?", "Warning", MessageBoxButtons.YesNo) = DialogResult.Yes Then
e.Cancel = False
Else
e.Cancel = True
End If
End Sub
InputBoxInputBox(Prompt [,Title] [, Default] [, Xpos] [, Ypos])
Xpos is the distance from the left edge of the screen, and Ypos is the distance from the top of the screen. Both are measured in twips (1/1440 th of an inch).
Note: The arguments are positional and optional. Enter a comma to skip an argument.
cityName = InputBox("Please enter city name:“, , “SF”)
If cityName = vbNullString Then
MessageBox.Show ("customer click cancel")
Else
Text1.Text = cityName
End If
Note: vbNullString is a VB keyword.
Text Box
• Useful properties– Locked: read only
– Password Character
– Multiline
– ScrollBar
– Text
• Useful events– TextChanged: default event
– Validating
Input Validation
• Numbers are checked to ensure they are:– Within a range of possible values– Reasonableness– Not causing problems such as division by 0.– Containing only digits
• IsNumeric
• Textbox:– Set CauseValidation property to true.– Use the Validating event:
• Triggered just before the focus shifts to other control.
TextBox Validating EventPrivate Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If Not IsNumeric(TextBox1.Text) Then
e.Cancel = True
MsgBox("enter digits only")
Else
MsgBox("good")
End If
End Sub
Note: Why not use theTextChanged event?
Group Box and Panel
• Controls in a Group Box should move with the boxs.
• A panel control can display scrollbars by setting the AutoScroll property to true.
Radio Button
• Radio buttons must be grouped together inside a container such as a GroupBox or a form.
• When the user selects an option all other options in the same group are deselected.
• Checked property value: True/False. • Default button: Set the Checked property to
true at the design time.
RadioButton Example 1
Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
If RadioButton1.Checked = True Then
MsgBox("Check RadioButton1")
Else
MsgBox("uncheck RadioButton1")
End If
End Sub
RadioButton Example 2
If radioButton1.Checked=true then
textbox1.text=“You select radio button 1”
ElseIf radioButton2.Checked=true then
textbox1.text=“You select radio button 2”
Else
textbox1.text=“You select radio button 3”
End If
Check Box
• Check boxes do not belong to a group even when they are grouped in a Group Box.
• Checked property and checkedChangedevent
Check Box Example 1Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked = True Then
MsgBox(“check chk1")
Else
MsgBox("uncheck chk1")
End If
End Sub
Check Box Example 2Dim msg as String
Msg=“You choose “
If checkBox1.checked=true then
msg=msg & “check box 1”
End If
If checkBox2.checked=true then
msg=msg & “check box 2”
End If
If checkBox3.checked=true then
msg=msg & “check box 3”
End If
Working with Strings
• String comparison is case-sensitive:– Blank– Digits in numerical order– Uppercase letters in alphabetical order– Lowercase letters in alphabetical order
• “A” <> “a”
• “a” > “Z”
• “alan”, “Chao”, “Smith”
String Methods
• ToUpper, ToLower• Length – Number of characters• TrimStart, TrimEnd, Trim• Substring(Start), Substring(Start, length)• IndexOf(SearchString), IndexOf(SearchString, Start)
– 0 based index– Case-sensitive
• eName=“David”• Position=eName.IndexOf(“d”)
– Return –1 if the searchString is not found.
• Note: Text property of a Textbox has all the string methods.– Ex. TextBox1.Text.Substring(0,2)
Example: Extract the firstname and the lastname from a fullname • Dim indexSpace As Integer• Dim firstName, lastName As String• indexSpace = TextBox1.Text.IndexOf(" ")• firstName = TextBox1.Text.Substring(0, indexSpace)
• lastName = TextBox1.Text.Substring(indexSpace + 1)
• MessageBox.Show(firstName)• MessageBox.Show(lastName)
Example: Validate SSN FormatPrivate Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
Dim correct As Boolean = True
If Not IsNumeric(TextBox1.Text.Substring(0, 3)) Or _
Not IsNumeric(TextBox1.Text.Substring(4, 2)) Or _
Not IsNumeric(TextBox1.Text.Substring(7, 4)) Then
correct = False
End If
If TextBox1.Text.Substring(3, 1) <> "-" Or TextBox1.Text.Substring(6, 1) <> "-" Then
correct = False
End If
If correct Then
MsgBox("perfect format")
Else
e.Cancel = True
MsgBox("not correct format")
End If
End Sub