Presentation is loading. Please wait.

Presentation is loading. Please wait.

VB.Net Loops.

Similar presentations


Presentation on theme: "VB.Net Loops."— Presentation transcript:

1 VB.Net Loops

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

3 Do While/Do Until Private Sub Command1_Click() Dim counter As Integer
Do While counter <= 5 Debug.Write(counter) counter = counter + 1 Loop Text1.Text = counter End Sub Private Sub Button2_Click() Do Until counter > 5

4 Loop Demo:Future Value
Dim 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.

5 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?

6 Dim i, j, wordCount As Integer
Dim trimedText As String trimedText = TextBox1.Text.Trim() wordCount = 0 If trimedText.Length = 0 Then 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 MessageBox.Show(wordCount.ToString & "words")

7 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 i = j + 1 If i >= searchText.Length Then Loop MessageBox.Show(wordCount.ToString & "words")

8 List Box Useful properties Methods Events: SelectedIndexChanged event
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

9 List Box Example Private 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

10 Selected Item’s Value Demo: Select interest rate from a list box.

11 ListBox Multiple Selections
Note: The SelectionMode property must set to multi selection. extBox2.Text = ListBox1.SelectedItems.Count.ToString Dim allSel As String Dim i As Integer For 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 String For Each item In ListBox1.SelectedItems allSel = allSel & item TextBox3.Text = allSel

12 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.

13 Using ListBox to Display Output
ListBox1.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

14 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?

15 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

16 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) End Sub

17 Structured Error Handling
Try result = Val(TextBox1.Text) / Val(TextBox2.Text) TextBox3.Text = result.ToString Catch except As DivideByZeroException MessageBox.Show(except.Message) Catch except As Exception Finally MessageBox.Show("I get exdecuted, no matter what") End Try

18 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”.

19 Using Collections Define a collection: Methods:
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.

20 Iterating Through a Collection
Dim 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

21 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

22 Enumerations Provide a way to associate meaningful names with a sequence of constant values. 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


Download ppt "VB.Net Loops."

Similar presentations


Ads by Google