Transcript COMP3100E

COMP3100E
Developing Microsoft .Net
Applications for Windows (Visual
Basic .Net)
Class 6
COMP3100e
1
Objectives
Q&A
Homework Assignment
Homework Solution
Sequential Files
COMP3100e
2
Collections

A collection is a set of similarly
typed objects that are grouped
together.

Objects of any type can be
grouped into a single collection of
the type Object to take
advantage of constructs that are
inherent in the language. For
example, for each in Visual Basic
expects all objects in the
collection to be of a single type.
COMP3100e
3

System.Collections classes can generally be
categorized into three types:
– Commonly used collections.
» These are the common variations of data
collections, such as hash tables, queues, stacks,
dictionaries, and lists. Commonly used collections
have generic versions and nongeneric versions.
– Bit collections.
» These are collections whose elements are bit
flags. They behave slightly differently from other
collections.
– Specialized collections.
» These are collections with highly specific
purposes, usually to handle a specific type of
element, such as StringDictionary.

Be sure to choose a collection class carefully.
Because each collection has its own
functionality, each also has its own limitations.
The more specialized a collection is, the more
limited it is.
COMP3100e
4
System.Collection
s
ArrayList Implements the IList interface using an array whose size is
dynamically increased as required.
BitArray Manages a compact array of bit values, which are represented
as Booleans, where true indicates that the bit is on (1) and false
indicates the bit is off (0).
CaseInsensitiveComparer Compares two objects for equivalence,
ignoring the case of strings.
CaseInsensitiveHashCodeProvider Supplies a hash code for an object,
using a hashing algorithm that ignores the case of strings.
CollectionBase Provides the abstract base class for a strongly typed
collection.
Comparer Compares two objects for equivalence, where string
comparisons are case-sensitive.
DictionaryBase Provides the abstract base class for a strongly typed
collection of key/value pairs.
Hashtable Represents a collection of key/value pairs that are organized
based on the hash code of the key.
Queue Represents a first-in, first-out collection of objects.
ReadOnlyCollectionBase Provides the abstract base class for a
strongly typed non-generic read-only collection.
SortedList Represents a collection of key/value pairs that are sorted by
the keys and are accessible by key and by index.
Stack Represents a simple last-in-first-out (LIFO) non-generic
collection of objects
COMP3100e
5
Collections
Public Class Form1
'Declare a variable of type Control to represent form
controls
Dim ctrl As Control
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
For Each ctrl In Controls
ctrl.Text = "Click Me!"
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button2.Click
For Each ctrl In Controls
ctrl.Left = ctrl.Left + 25
Next
End Sub
Private Sub btnMoveObjects_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnMoveObjects.Click
For Each ctrl In Controls
If ctrl.Name <> "btnMoveObjects" Then
ctrl.Left = ctrl.Left + 25
End If
Next
End Sub
6
COMP3100e
End Class
Collections
(Continued)
Property
Count
Read-only. Returns an Integer containing the
number of elements in a Visual Basic collection.
Item
Read-only. Returns a specific element of a
Visual Basic Collection object either by position
or by key.
Method
Add
Adds an element to a Visual Basic Collection
object.
Clear
Removes all elements from a Visual Basic
Collection object.
Contains
(Collection
Object)
Returns a Boolean indicating whether a Visual
Basic Collection object contains an element
with a specific key.
GetEnumerator
Returns an enumerator object for iterating over
the collection.
Remove
Removes an element from a Visual Basic
Collection object.
COMP3100e
7
Basics of SF
 Choose a name for the file
 Choose a name to be used to refer to
the file
 open the file
Dim sw As IO.StreamWriter = _
IO.File.CreateText("PIONEERS.TXT")
Dim sr As IO.StreamReader = _
IO.File.OpenText("PIONEERS.TXT")

Interact with the file
sr.ReadLine
sw.WriteLine("Atanasoff“)

close the file
– sr.Close()
– sw.Close()
COMP3100e
8
Basics Continued


The .NET System.IO namespace includes a class library that
facilitates string, character, and file manipulation.
These classes contain properties, methods, and events for
creating, copying, moving, and deleting files.
−

As both strings and numeric data types are supported, they also
allow you to incorporate data types in files.
The most commonly used classes are:
−
−
−
−
−
FileStream
BinaryReader
BinaryWriter
StreamReader
StreamWriter
COMP3100e
9
Basics Continued
 If file is opened for output and it already
exists, the existing file is erased.
 If a file is opened for input and it doesn’t
exist, the program is forever cursed and it’s
programmer is delegated to writing lesser
spells.
– If IO.File.Exists(Filename) is true, then the file
exists
 The method “Peek” is commonly used to
determine when the end of file is
encountered (equal to a -1)
COMP3100e
10
The Three Modes
CreateText
Dim sw As IO.StreamWriter = _
IO.File.CreateText("PIONEERS.TXT")
OpenText
Dim sr As IO.StreamReader = _
IO.File.OpenText("PIONEERS.TXT")
Dim sr As StreamReader
' Open the file to read.
Sr = File.OpenText("c:\MyFile.txt")
AppendText

Dim sw As IO.StreamWriter = _
IO.File.OpenText("PIONEERS.TXT")
COMP3100e
11
Simplified IO
 After OPTION Strict ON, insert
– Imports System.IO
– Then you don’t have to say IO. All the time…
 File.Delete (filename)
 File.Move(oldname, newname)
COMP3100e
12
Output example
'Create the file PIONEERS.TXT
Dim sw As IO.StreamWriter = _
IO.File.CreateText("PIONEERS.TXT")
With sw
.WriteLine("Atanasoff")
.WriteLine("Babbage")
.WriteLine("Codd")
.WriteLine("Dijkstra")
.WriteLine("Eckert")
.WriteLine("Faggin")
.WriteLine("Gates")
.WriteLine("Hollerith")
.Close()
End With
COMP3100e
13
Input Example
'Display the contents of the file
'PIONEERS.TXT
in a list box
Dim sr As StreamReader=
File.OpenText("PIONEERS.TXT")
lstNames.Items.Clear()
Do While sr.Peek <> -1
lstNames.Items.Add(sr.ReadLine)
Loop
sr.Close()
COMP3100e
14
Append
(Your Teacher)
'Add a person's name and year of 'birth
to file
Dim message As String
Dim sw as StreamWriter
If (txtName.Text <> "") And _
(txtYOB.Text <> "") Then
sw = File.AppendText("YOB.TXT")
sw.WriteLine(txtName.Text)
sw.WriteLine(txtYOB.Text)
sw.Close()
txtName.Clear()
txtYOB.Clear()
txtName.Focus()
Else
message = "You must enter a name and” *
_
“ year of birth."
MsgBox(message, , "Information “ & _
“Incomplete")
End If
COMP3100e
15
Change items
Dim sr As IO.StreamReader = _
IO.File.OpenText(“COWBOY.TXT")
Dim sw As IO.StreamWriter = _
IO.File.CreateText(“COWBOY3.TXT")
Dim item as string
Dim price as single
Do While sr.Peek <> -1
item = sr.readline
price= sr.readline
If item = "Saddle" Then
price = price * 0.8
End If
sw.writeline (item)
sw.writeline (price)
Loop
sr.close
sw.close
MsgBox "New price updated in “ & _
“COWBOY3.TXT", , ""
COMP3100e
16
Delete from files
Dim sr As IO.StreamReader = _
IO.File.OpenText(“COWBOY.TXT")
Dim sw As IO.StreamWriter = _
IO.File.CreateText(“COWBOY3.TXT")
Dim item as string
Dim price as single
Do While sr.Peek <> -1
item = sr.readline
price= sr.readline
If item <> "Saddle" Then
sw.writeln (item)
sw.writeln (price)
End If
Loop
sr.close
sw.close
MsgBox “Saddle removed from “ & _
“COWBOY3.TXT", , ""
COMP3100e
17
Structures
Structure Individual
Dim name As String
Dim yearBorn As Integer
End Structure
Private Sub btnSort_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnSort.Click
'Sort data from YOB.TXT file by year of
birth
Dim numPeople As Integer
Dim person(numPeople) As Individual
numPeople = NumberOfRecords("YOB.TXT")
ReadData(person, numPeople)
SortData(person, numPeople)
ShowData(person, numPeople)
WriteData(person, numPeople)
End Sub
COMP3100e
18
Structures Continued
Function NumberOfRecords(ByVal
filespec As String) As Integer
Dim
Dim
Dim
Dim
name As String
yearBorn As Integer
n As Integer 'Used to count records
sr as IO.StreamReader
n = 0
File.OpenText(filespec)
Do While (sr.Peek <> -1)
name = sr.ReadLine
yearBorn = CInt(sr.ReadLine)
n += 1
'Increase n by 1
Loop
sr.Close()
Return n
End Function
COMP3100e
19
Reading into an Array
Sub ReadData(ByRef person()
As Individual, ByVal
numPeople As Integer)
'Read data from file into arrays
Dim index As Integer
Dim sr As IO.StreamReader =
IO.File.OpenText("YOB.TXT")
For index = 1 To numPeople
person(index).name = sr.ReadLine
person(index).yearBorn = CInt(sr.ReadLine)
Next
sr.Close()
End Sub
COMP3100e
20
Sorting
Sub SortData(ByRef person() As
Individual, ByVal numPeople As
Integer)
'Bubble sort arrays by year of birth
Dim passNum, index As Integer
For passNum = 1 To numPeople - 1
For index = 1 To numPeople - passNum
If person(index).yearBorn > _
person(index + 1).yearBorn Then
SwapData(person, index)
End If
Next index
Next passNum
End Sub
COMP3100e
21
Showing data in Listbox
Sub ShowData(ByVal person() As
Individual, ByVal numPeople As
Integer)
'Display the sorted list
Dim index As Integer
lstShowData.Items.Clear()
For index = 1 To numPeople
lstShowData.Items.Add(person(index).name
& "
" & person(index).yearBorn)
Next
End Sub
Sub SwapData(ByRef person() As
Individual, ByVal index As Integer)
Dim temp As Individual
temp = person(index)
person(index) = person(index + 1)
person(index + 1) = temp
End Sub
COMP3100e
22
Saving Data into a file
Sub WriteData(ByVal person()
As Individual, ByVal
numPeople As Integer)
'Write data back into file
Dim index As Integer
Dim sr As IO.StreamWriter =
IO.File.CreateText("YOB2.TXT"
)
For index = 1 To numPeople
sr.WriteLine(person(index).name)
sr.WriteLine(person(index).yearBorn)
Next
sr.Close()
End Sub
COMP3100e
23
The My Object
5
objects available
– Application
– Computer
– Form
– User
– WebServices
COMP3100e
24
Example of My
Public Class Form1
Private Sub Form1_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
MsgBox(My.User.Name)
End Sub
End Class
COMP3100e
25