VB Collection Data Structures

1 / 34

# VB Collection Data Structures - PowerPoint PPT Presentation

VB Collection Data Structures Array ArrayList HashTable VB6 Collection Others:SortedList, Stack, Queue Arrays Declaring a Array With subscript: Dim numbers(2) as Integer Using variable as subscript: Dim arrayIndex as Integer = 10 Dim myArray(arrayIndex) as Integer Without subscript

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'VB Collection Data Structures' - andrew

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### VB Collection Data Structures

Array
• ArrayList
• HashTable
• VB6 Collection
• Others:SortedList, Stack, Queue

### Arrays

Declaring a Array
• With subscript:
• Dim numbers(2) as Integer
• Using variable as subscript:
• Dim arrayIndex as Integer = 10
• Dim myArray(arrayIndex) as Integer
• Without subscript
• Dim numbers() as Integer = {2, 4, 6}
• Dim someNames() as String = {“”, “”, “”}
• Note: Can not have a subscript with a initialization list.
• Without subscript and initialization
• Dim numbers As Integer()
• numbers = New Integer() {2, 4, 6}
Accessing Array Elements with a For … Next Loop
• Dim i As Integer = 0, sum As Integer = 0
• For i = 0 To 2
• sum += numbers(i)
• Next
• GetUpperBound
• For i = 0 to numbers.GetUpperBound(0)

sum += numbers(i)

• Next
• Length
• For i = 0 to numbers.length-1

sum += numbers(i)

• Next
Accessing Array Elements with a For Each Loop

Dim i As Integer

For Each i In numbers

i = i * 2

MessageBox.Show(i.ToString)

Next

Array’s Properties and Methods
• Properties:
• Length
• IsFixedSize
• Methods
• Clear
• Clone, Copy, CopyTo
• GetLowerBound, GetUpperBound
• Reverse
• Sort
Highest Values in a Array

Dim highest As Integer

highest = numbers(0)

For i = 1 To numbers.GetUpperBound(0)

If numbers(i) > highest Then

highest = numbers(i)

End If

Next

Searching Arrays

Dim found As Boolean = False

Dim searchValue As Integer

searchValue = InputBox("Enter search value: ")

For i = 0 To numbers.GetUpperBound(0)

If numbers(i) = searchValue Then

found = True

Exit For

End If

Next

If found Then

MsgBox("Number found")

Else

End If

Searching with the IndexOf Method

If numbers.IndexOf(numbers, InputBox("Enter search value: ")) < 0 Then

MessageBox.Show("not exist")

Else

MessageBox.Show("exist")

End If

Using Parallel Relationship between Array and Listbox

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

phone(0) = "1234"

phone(1) = "6789"

phone(2) = "3456"

End Sub

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

MessageBox.Show(ListBox1.SelectedItem & "phone is" & phone(ListBox1.SelectedIndex))

End Sub

ReDim
• ReDim numbers(5)
• Original values in the array will be lost.
• ReDim Preserve numbers(5)
• Use ReDim to assign size if the array is declared without subscript.
• Dim test As Integer()
• ReDim test(2)
Passing Arrays as Arguments

Dim outstr As String

setnew(test)

For i = 0 To test.GetUpperBound(0)

outstr &= test(i).ToString & vbCrLf

Next

MessageBox.Show(outstr)

End Sub

Sub setnew(ByVal a() As Integer)

Dim i As Integer

For i = 0 To a.GetUpperBound(0)

a(i) = 0

Next

End Sub

Note: ByVal or ByRef? With ByVal, it will prevent an array argument from being assigned to another array.

Two-Dimensional Arrays
• Depts=1
• Prods=2
• Dim SalesData(Depts, Prods) As Double
• With initialization
• Dim SalesData(,) as Double = {{20,30,15},{40,32,55}}
For Each Loops for 2-dimensional Array

Dim salesData(,) As Double = {{20, 15, 30}, {30, 21, 50}}

Dim totalSales, I As Double

For Each I In salesData

totalSales += I

Next

TextBox1.Text = totalSales.ToString

For Next Loops for 2-dimensional Array

Dim row, col As Integer

For row = 0 To salesData.GetUpperBound(0)

For col = 0 To salesData.GetUpperBound(1)

totalSales += salesData(row, col)

Next

Next

MessageBox.Show(totalSales.ToString)

Problem: How to compute total sales by Department? by Product?

Data Binding with Arrays
• Connect a control to one data source.
• Arrays can be used as data source for a control.
• Demo: ListBox DataSource property.
• Dim fruits() As String = {"Apple", "Orange", "Banana", "Strawberry", "Kiwi"}
• ListBox1.DataSource = fruits
Other Collections
• More flexible than array:
• No need to declare the number of objects in a collection.
• Objects can be added, deleted at any position.
• Can store any types of data.
ArrayList
• Define an arraylist:
• Dim myArrayList As New ArrayList()
• Properties:Count, Item, etc.
• myArrayList.Item(0) 0-based index
• Methods:
• Clear, Add, Insert, Remove, RemoveAt, Contains, IndexOf, etc.
ArrayList Demo

Dim testArrayList As New ArrayList()

Dim Fruits() As String = {"Apple", "orange", "Banana"}

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

Dim f2 As New Form2()

TextBox1.Text = testArrayList.Item(0)

TextBox2.Text = testArrayList.Item(1).ToString

TextBox3.Text = testArrayList.Item(2)(1)

TextBox4.Text = testArrayList.Item(3).Age

End Sub

For Each Loop with ArrayList

Dim testArrayList As New ArrayList()

Dim f2 As New DataForm2()

Dim Fruits() As String = {"Apple", "orange", "Banana"}

Dim myObj As Object

For Each myObj In testArrayList

MessageBox.Show(myObj.GetType.ToString)

Next

Data Binding with ArrayLists
• Arraylists can be used as data source for a control.
• Demo: ListBox DataSource property.
• Dim myArrayList As New ArrayList()
• ListBox1.DataSource = myArrayList

Spelling Checker Example

Dim wordList As New ArrayList

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

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Try

Dim re As Regex

re = New Regex("\w+")

Dim source As String

source = txtSource.Text

Dim mc As MatchCollection = re.Matches(source)

Dim m As Match

Dim result As String

For Each m In mc

If Not wordList.Contains(m.Value) Then

result += m.ToString & vbCrLf

txtSource.Select(txtSource.Text.IndexOf(m.ToString), m.Length)

MessageBox.Show("next")

End If

Next

MessageBox.Show("Invalid words: " & vbCrLf & result)

Catch ex As System.Exception

MessageBox.Show(ex.Message)

End Try

End Sub

HashTable
• The HashTable collection provides very fast look-up.
• Each element in a HashTable is a DictionaryEntry type containing a pair of Key and Value.
• Properties:Count, Item, Keys, Values
• myHashTable.Item(key)
• Methods:
• Clear, Add, Remove,ContainsKey, ContainsValue, etc.
• Note 1: Elements in a HashTable are stored according to the hash value of keys.
• Note 2: Keys must be unique.
HashTable Example

Dim myHashTable As New Hashtable()

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

Dim myKey As String

For Each myKey In myHashTable.Keys

Next

End Sub

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

MessageBox.Show(myHashTable.Item(ListBox1.SelectedItem))

End Sub

Dim searchKey As String

searchKey = InputBox("enter key")

If myHash.ContainsKey(searchKey) Then

TextBox1.Text = myHashTable.Item(searchKey)

Else

MessageBox.Show("key not exists")

End If

VB 6 Collections
• Define a collection:
• Ex. Dim Pets as New Collection
• Methods:
• Add an object with a key:
• 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 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

Timer
• Event:
• Tick
• Property:
• Enable
• Interval property
• measured in millisecond, 1000 millis = 1 second
• Methods:
• Start
• Stop
Status Bar & Timer
• Status Bar
• Panels property (collection)
• Set ShowPanel property to true.
• StatusBar1.ShowPanels = True
• StatusBarPanel1.Text = System.DateTime.Now.ToString
• Timer
• Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick StatusBarPanel1.Text = System.DateTime.Now.ToString

End Sub

Bitmap Data Type
• To read a picture file to program:
• Dim pic as New Bitmap(“c:\mypic.jpg”)
Rotate Form’s Background Image

Create a collection of pictures:

Dim pcol As New ArrayList

Dim im2 As New Bitmap("c:\Flyaway.jpg")

Dim im3 As New Bitmap("c:\SnowTrees.jpg")

Use Timer to change image

Dim pcol As New ArrayList

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

Dim im2 As New Bitmap("c:\Flyaway.jpg")

Dim im3 As New Bitmap("c:\SnowTrees.jpg")

End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

Static counter As Integer

Me.BackgroundImage = pcol.Item(counter)

counter += 1

counter = (counter Mod 3)

End Sub