Programming Concepts: A Guide to Loops, Arrays, and File Handling

Programming Control Do-While Loops

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

Dim num As Integer

num = 1

txtResult.Clear()

Do While num <= 7

txtResult.AppendText(CStr(num) & vbCrLf)

num = num + 1

Loop

End Sub

Do-Until Loops

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

Dim num As Integer

num = 6

txtResult.Clear()

Do

txtResult.AppendText(CStr(num) & vbCrLf)

num = num + 1

Loop Until num <= 7

End Sub

Subroutines

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

Dim x, y As Double ‘x and y are changed by GetNumbers so that DisplaySum can use the updated values

GetNumbers(x, y)

DisplaySum(x, y)

End Sub

Sub GetNumbers(ByRef x As Double, ByRef y As Double)

‘Get the numbers from the textboxes and store as x and y

x = CDbl(txtX.Text)

y = CDbl(txtY.Text)

End Sub

Sub DisplaySum(ByVal x As Double, ByVal y As Double)

Dim sum As Double

sum = x + y

txtResult.Text = CStr(sum)

End Sub

For Next Loops

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

Dim i As Integer

txtResult.Clear()

For i = 1 To 5 Step 1

txtResult.AppendText(CStr(i * 2) & vbCrLf)

Next

End Sub

Function

Function FtoC(ByVal t As Double) As Double

‘Convert Fahrenheit temperature to Celsius

Dim C As Double

C = (5 / 9) * (t – 32)

Return C

End Function

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

Dim Celsius, Fahrenheit As Double

Fahrenheit = CDbl(txtTempF.Text)

Celsius = FtoC(Fahrenheit)

txtTempC.Text = CStr(Celsius)

End Sub

Array

Dim students(29) As String

If we don’t say how many elements are in the array we can do that later using the ReDim command.

Dim students() As String

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

ReDim students(4)

students = {“Dave”, “John”, “Betty”, “Steve”, “Matthew”}

ReDim Preserve

End Sub

Searching for an Element in an Array

Array.IndexOf(arrayName, value) – returns the index of the first occurance of value in arrayName.

Passing an Array to a Function

eg. Function FirstStudent(ByVal students() As String) As String

This function returns a string (with the first students name – single string, NOT an array). The function is sent the array students().

Function Returns an Array

eg. Function GetGrades(ByVal numGrades As Integer) As Double()

This function returns an array of doubles. The function is sent a single integer.

Manually Finding the Maximum

Dim students(6) As String

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

Dim max As String

Dim numStudents As Integer

students = {“Dave”, “John”, “Betty”, “Steve”, “Matthew”, “Aaron”, “Patricia”}

numStudents = students.Count

lstStudents.Items.Clear()

max = students(0)

For i As Integer = 1 To (numStudents – 1)

If students(i) > max Then

max = students(i)

End If

Next

lstStudents.Items.Add(max)

End Sub

Performing a Manual Sort

Dim students(6) As String

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

Dim temp1 As String

Dim count As Integer = 0

Dim numStudents As Integer

students = {“Dave”, “John”, “Betty”, “Steve”, “Matthew”, “Aaron”, “Patricia”}

numStudents = students.Count

lstStudents.Items.Clear()

‘ListBox1.Items.Add(CStr(numStudents))

For j As Integer = 1 To (numStudents – 1)

For i As Integer = 1 To (numStudents – 1 – count)

If students(i) < students(i – 1) Then

temp1 = students(i – 1)

students(i – 1) = students(i)

students(i) = temp1

End If

Next

count = count + 1

Next

For i As Integer = 0 To (numStudents – 1)

‘Array.Sort(students)

lstStudents.Items.Add(students(i))

Next

End Sub

Reading a File Directly into a List Box

In the following example we open a file (I chose a file called Months.txt) and display the resutls in a list box.

Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click

Dim textfile As String

OpenFileDialog1.Filter = “All Files (*.*) | *.* | Text Files (*.txt) | *.txt”

OpenFileDialog1.ShowDialog()

textfile = OpenFileDialog1.FileName

lstDisplay.DataSource = IO.File.ReadAllLines(textfile)

lstDisplay.SelectedItem = Nothing

End Sub

Reading:

Dim textfile As String

Dim strLineRead As String

Dim srReadVariable As IO.StreamReader ‘Make a variable of type StreamWriter

OpenFileDialog1.Filter = “Text Files (*.txt) | *.txt” ‘Show only text files to open

OpenFileDialog1.ShowDialog() ‘Show the open file dialog window

textfile = OpenFileDialog1.FileName ‘Save the filename and path to a string variable

srReadVariable = IO.File.OpenText(textfile) ‘Create a stream reader to the file

Do Until srReadVariable.EndOfStream ‘Until the end of the file is reached

strLineRead = srReadVariable.ReadLine ‘Read a line of the file and save it to a variable

lstDisplay.Items.Add(strLineRead) ‘Display the line of the file in the textbox.

Loop ‘Repeat Loop

srReadVariable.Close() ‘Close the stream reader – very important.

Writing:

Dim textfile As String

Dim swWriteVariable As IO.StreamWriter ‘Make a variable of type StreamWriter

SaveFileDialog1.Filter = “Text Files (*.txt) | *.txt” ‘Show only text files in the save file dialog

SaveFileDialog1.ShowDialog() ‘Show the save file dialog window

textfile = SaveFileDialog1.FileName ‘Save the file name in a string variable

swWriteVariable = IO.File.CreateText(textfile) ‘Create a stream writer to the file

swWriteVariable.WriteLine(txtEnterData.Text) ‘Write the textbox text into the file

swWriteVariable.Close() ‘Close the stream reader – very important.

Code

Imports System.Drawing.Printing

Public Class Form1

Dim pSize As PaperSize

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

Dim InstPrinters As String

‘ Find all printers installed

For Each InstPrinters In PrinterSettings.InstalledPrinters

cboPrinters.Items.Add(InstPrinters)

Next InstPrinters

‘ Set the combo to the first printer in the list

cboPrinters.SelectedIndex = 0

‘ Put the available paper sizes in a combo box for the user to select

For i = 0 To PrintDocument1.PrinterSettings.PaperSizes.Count – 1

pSize = PrintDocument1.PrinterSettings.PaperSizes.Item(i)

cboPaperSize.Items.Add(pSize)

Next

End Sub

Private Sub btnPrintPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrintPreview.Click

PrintPreviewDialog1.Document = PrintDocument1

PrintPreviewDialog1.ShowDialog()

End Sub

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

Dim grtext As Graphics = e.Graphics ‘Declars grtext as a graphics object capable of printing both text and graphics

Dim font As New Font(“Courier New”, 12, FontStyle.Italic) ‘Define a font that we can use later

‘Now we tell the program what we want to be printed in PrintDocument1

grtext.DrawString(txtToPrint.Text, Me.Font, Brushes.Black, 100, 150) ‘Uses the forms Font.

grtext.DrawString(txtToPrint.Text, font, Brushes.Red, 100, 300) ‘ Uses the font we made

grtext.DrawString(“This is a test page”, Me.Font, Brushes.Brown, 100, 350)

End Sub

Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click

PrintDocument1.PrinterSettings.PrinterName = cboPrinters.Text ‘Set the printer name to the selected printer

PrintDocument1.DefaultPageSettings.PaperSize = pSize ‘set the paper size to what the user selected

‘PrintDocument1.DefaultPageSettings.PaperSize = PrintDocument1.PrinterSettings.PaperSizes.Item(0)

PrintDocument1.Print()

End Sub

End Class