22
VB.Net Loops

VB.Net Loops. Loop FOR index – start TO end [STEP step] [statements] [EXIT FOR] NEXT index DO [{WHILE| UNTIL} condition] [statements] [EXIT DO] LOOP

  • View
    243

  • Download
    2

Embed Size (px)

Citation preview

VB.Net Loops

Loop

• FOR index – start TO end [STEP step]

[statements]

[EXIT FOR]

NEXT index

DO [{WHILE| UNTIL} condition]

[statements]

[EXIT DO]

LOOP

Do While/Do UntilPrivate Sub Command1_Click()Dim counter As Integercounter = 0Do While counter <= 5 Debug.Write(counter) counter = counter + 1LoopText1.Text = counterEnd Sub

Private Sub Button2_Click() Dim counter As Integercounter = 0Do Until counter > 5 Debug.Write(counter) counter = counter + 1LoopText1.Text = counterEnd Sub

Loop Demo:Future ValueDim output As String = "Year" & vbTab & "FutureValue" & vbCrLf

Dim output2 As String = "Year" & vbTab & "FutureValue" & vbCrLf

Dim amount, principal, iRate, year As Single

Dim yearIndex As Integer

principal = CSng(TextBox1.Text)

iRate = CSng(TextBox2.Text)

year = CSng(TextBox3.Text)

For yearIndex = 1 To CInt(year)

amount = principal * (1 + iRate) ^ yearIndex

output = output & yearIndex & vbTab & FormatCurrency(amount) & vbCrLf

output2 = output2 & yearIndex & vbTab & String.Format("{0:c}", amount) & vbCrLf

Next

MessageBox.Show(output, "FutureValue", MessageBoxButtons.OK)

MessageBox.Show(output2, "FutureValue", MessageBoxButtons.OK)

Note: Use the Do While, Do Until loops.

Note: vbCrLf is a VB keyword for a new line.

Example: Display characters entered in textbox1one at a time

• Dim index As Integer• index = 0• For index = 0 To TextBox1.TextLength - 1

MessageBox.Show(TextBox1.Text.Substring(index, 1))

• Next

• Problem 1: How many “a” entered in textbox1?• Problem 2: How many words entered in textbox1?

Dim i, j, wordCount As Integer

Dim trimedText As String

trimedText = TextBox1.Text.Trim()

wordCount = 0

If trimedText.Length = 0 Then

wordCount = 0

Else

For i = 0 To trimedText.Length - 1

If trimedText.Substring(i, 1) = Chr(Keys.Space) Then

wordCount += 1

For j = i To trimedText.Length - 1

If Not trimedText.Substring(j, 1) = " " Then

i = j

Exit For

End If

Next

End If

Next

wordCount += 1

End If

MessageBox.Show(wordCount.ToString & "words")

Dim i As Integer = 0 Dim j As Integer Dim wordCount As Integer = 0 Dim searchText As String searchText = TextBox1.Text If searchText.Length > 0 Then Do While True j = searchText.IndexOf(" ", i) If j < 0 Then wordCount += 1 Exit Do End If If j = i Then i += 1 Else wordCount += 1 i = j + 1 End If If i >= searchText.Length Then Exit Do End If Loop End If MessageBox.Show(wordCount.ToString & "words")

List Box

• Useful properties– Items: The items in the listBox. It is a collection

strcture. Items can be entered at the design time or entered with code.

– SelectionMode: one or multi selection– SelectedItem(s), SelectedIndex

• Methods– Add– Clear

• Events: SelectedIndexChanged event

List Box ExamplePrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load

TextBox1.Clear()

TextBox2.Clear()

ListBox1.Items.Clear()

ListBox1.Items.Add("Apple")

ListBox1.Items.Add("Orange")

ListBox1.Items.Add("Banana")

ListBox1.Items.Add("Strawberry")

TextBox2.Text = ListBox1.Items.Count.ToString

End Sub

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

TextBox1.Text = ListBox1.SelectedItem

End Sub

Selected Item’s Value

• Demo:– Select interest rate from a list box.

ListBox Multiple SelectionsNote: The SelectionMode property must set to multi selection.

extBox2.Text = ListBox1.SelectedItems.Count.ToStringDim allSel As StringDim i As IntegerFor i = 0 To ListBox1.SelectedItems.Count - 1 allSel = allSel & ListBox1.SelectedItems.Item(I) Or allSel = allSel & ListBox1.SelectedItems(I)

Next ‘**** Or use the For Each loop****Dim item As StringFor Each item In ListBox1.SelectedItems allSel = allSel & item NextTextBox3.Text = allSel

ListBox Items Collections• Methods:

– ADD: ListBox1.Items.Add("Apple")

– Item: Retrieve an object from Items• ListBox1.Items.Item(Index)

• ListBox1.Items(Index)

• 0-based index

– Insert: ListBox.Items.Insert(Index, item)

– Remove: Delete an object with a position index or key.• ListBox.Items.Remove(Item)

• ListBox.Items.RemoveAt(Index)

– Listbox1.Refresh()

– Clear: ListBox.Items.Clear()

– Count: Return the number of objects in a collection.

Using ListBox to Display OutputListBox1.Items.Clear()

ListBox1.Items.Add("Year" & vbTab & "FutureValue")

For yearIndex = 1 To CInt(year)

amount = principal * (1 + iRate) ^ yearIndex

ListBox1.Items.Add(yearIndex.ToString & vbTab & FormatCurrency(amount))

Next

ComboBox• Allows the user to type text directly into the

combo box.• Use the Text property to get entered item:

– ComboBox1.Text– The index for an entered item is –1.– SelectedItem may be different from the Text property.

• Search an item in the list: ComboBox1.Items.IndexOf(“search text”)– Found: return the index of the search text.– Not found: return –1.

• How to add an entered item to the list?

Unstructured Error Handling• On Error GoTo errorhandler (a label)• Built-in Err object properties:

– Number – Error number

– Source – Name of VB ile in which error occurred

– Description – error message

• Continue the program execution:– Resume: returns execution to the statement that caused

the error.

– Resume Next

– Resume label: Jumps to the line containing the label.

– Exit Sub

Error Handling Example

Private Sub cmdDivide_Click()

On Error GoTo DivideErrorHandler

lalAnswer.Caption=CStr(CDbl(Text1.text)/CDbl(Text2.Text))

Exit Sub

DivideErrorHandler:

MsgBox(CStr(Err.Number) & “: “ & Err.Description)

Exit Sub

End Sub

Structured Error HandlingTry

result = Val(TextBox1.Text) / Val(TextBox2.Text)

TextBox3.Text = result.ToString

Catch except As DivideByZeroException

MessageBox.Show(except.Message)

Catch except As Exception

MessageBox.Show(except.Message)

Finally

MessageBox.Show("I get exdecuted, no matter what")

End Try

Collections

• Collections are used to store lists of objects.• More flexible than array:

– No need to declare the number of objects in a collection.

– Objects can be added, deleted at any position.

– Object can be retrieved from a collection by a key.

– Can store different types of objects.

• A collection’s name usually end with a “s”.

Using Collections• Define a collection:

– Ex. Dim Pets as New Collection

• Methods:– ADD: Add object to a collection

• Pets.Add(“dog”)• Add an object with a key:

– Pets.Add(“Dog”, “D”)

– Item: Retrieve an object from a collection with a position index (base 1) or with a key.

• petName = Pets.Item(1)• petName = Pets.Item(“D”)

– Count: Return the number of objects in a collection.– Remove: Delete an object with a position index or key.

Iterating Through a CollectionDim Pets as New Collection

Dim Indx as Long

For Indx = 1 to Pets.Count

…operations …

Next Indx

For Each pet in Pets

… operations …

Next pet

Enumerations

• Provide a way to associate meaningful names with a sequence of constant values.

• Define an enumeration using an Enum statement in classes, modules, and structures.– Private Enum seasonOfYear– Spring = 1– Summer = 2– Fall= 3– Winter = 4– End Enum

Enumerations

Enum enumTest

spring = 1

summer

fall

winter

End Enum

Dim etest As enumTest

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

etest = enumTest.summer

TextBox1.Text = Val(etest).ToString

•Provide a way to associate meaningful names with a sequence of constant values.