26
Chapter 7 Lists, Loops, and Printing Programming In Visual Basic.NET

Chapter 7 Lists, Loops, and Printing Programming In Visual Basic.NET

  • View
    225

  • Download
    0

Embed Size (px)

Citation preview

Chapter 7Lists, Loops, and

Printing

Programming In

Visual Basic.NET

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 2

• Provide a list for the user to select from

• ListBox tool– 1st prefix– Simple List Box with/without scroll bars

• ComboBox tool– cbo prefix– List may allow for user to add new items– List may "drop down" to display items in list

CheckedListBox not covered in this text

List Controls

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 3

List Controls Visually

ListBoxes

DropDownCombo Box

SimpleCombo Box

DropDownListCombo Box

• Special Combo Box Properties:– DropDownStyle

– Text

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 4

Choosing List Type

• Many items, little space– Dropdown Combo Box– Dropdown List

• Few items – List Box

• User allowed to add to the list– Simple Combo Box– Dropdown Combo Box

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 5

Items Collection

• List of items in a ListBox or ComboBox is a collection

• Collections are objects that have properties and methods that allow you to

– Add items– Remove items– Refer to individual items: read/modify them– Count items– Clear the collection

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 6

Filling List - Design Time

Click ellipses

button to open

Using the Items property

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 7

Properties of Items Collection

• Items.Index property– zero based value identifying individual items

• Items.SelectedIndex property– Identifies currently selected item in the list– If no item is selected ListIndex = -1

• Items.Count property– Stores the number of items in the list

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 8

lstSchools.Items(5) = "USC"

Accessing/Changing an Item

• Using index– To access item’s value

– To change item’s value

strSchool = lstSchools.Items(5)

‘Referencing the currently selected itemstrSelectedFlavor = lstFlavor.Items(lstFlavor.SelectedIndex)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 9

Adding Item to Items: Run Time

• Items.Add method– General Form– Examples

• Items.Insert method– General Form– Examples

Object.Items.Add (ItemValue)

lstNames.Items.Add ("Brandon")lstDeptNums.Items.Add (100)cboMajors.Items.Add (txtMajors.Text)cboGrade.Items.Add (cboGrade.Text)

Object.Items.Insert(IndexPosition, ItemValue)

lstDeptNums.Items.Insert (1, 100)cboGrade.Items.insert (0, "Freshman")cboMajors.Items.Insert (11, txtMajors.Text)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 10

Removing Item from Items

• Items.RemoveAt method– General Form– Examples

• Items.Remove method– General Form– Examples

lstDeptNums.Items.RemoveAt(1)

' Removing the currently selected itemcboGrade.Items.RemoveAt(cboGrade.SelectedIndex)

Object.Items.RemoveAt(IndexPosition)

Object.Items.Remove(TextString)

lstDeptNums.Items.Remove("USC")

' Removing the currently selected itemcboGrade.Items.Remove(cboGrade.Text)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 11

Clearing Items

• Items.Clear method– General Form

– Examples lstDeptNums.Items.Clear( )cboGrade.Items.Clear( )

Object.Items.Clear( )

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 12

ListBox and ComboBox Events

• TextChanged Event– Occurs when user types text into Combo– ListBox does not have TextChanged Event

• SelectedIndexChanged Event

• Enter Event (receive focus)

• Leave Event (lose focus)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 13

Loops

• Repeating a series of instructions

• Each repetition is called an iteration

• Types of Loops– Do

• Use when the number of iterations is unknown

– For Next• Use when the number of iterations is known

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 14

Do Loops• Ends based on a condition you specify:

– Do While a condition is True Loop– Do Until a condition becomes True Loop

• Condition Pretest vs. Posttest

Do {While |Until} conditionStatements to execute

Loop

Condition Pretest:May not run at all

Condition Posttest:Runs at least once

DoStatements to execute

Loop {While | Until} condition

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 15

Do Loops• Example:

Dim blnFound As Boolean = False Dim intIndex As Integer = 0 Do Until blnFound Or intIndex =

lstFlavors.Items.Count If txtFlavor.Text = lstFlavors.Items(intIndex) Then

blnFound = True End IfintIndex += 1

Loop If blnFound Then

MessageBox(“The item is in the list”)Else

MessageBox(“The item is not found””)End If

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 16

For Next Loops• Use when you know the number of iterations

– General Form

– Example

For LoopIndex = InitialValue To TestValue [Step Increment]

Statements to executeNext [LoopIndex]

Private Function lngFactorial(ByVal intInteger As Integer) As Long Dim intIndex As Integer lngFactorial = 1 'initialize function's value (default is 0) For intIndex = 1 To intInteger

lngFactorial *= intIndex Next intIndex

End Function

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 17

Examples of the For clausesFor intIndex = 10 To -10 Step –2 'negative

increment For sngRate = .05 to .2 Step .01 'decimal increment For intCounter = 0 to cboCoffee.Items.Count - 1 'expression

test value For intIndex = 10 to 0 'no iterations

'Enless loop. For intIndex = 1 to 5 ‘

‘Lines of codeintIndex = 1 'changing loop index is a poor programming style

Next intIndex

'Exiting For/Next Loops For intIndex = 1 to 5

If blnFound = True Then Exit For ‘Lines of code

Next intIndex

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 18

Printing a document in VB.NET

• PrintDocument control to print to printer

• PrintPreviewDialog control to preview printed document

• Crystal Reports is a utility packaged with the VB Professional and Enterprise Editions for creating reports from database files

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 19

PrintDocument Control

• PrintDocument control (prt)

• PrintPreviewDialog control (ppd)

• Both appear in the Component Tray of a form

• To start printing to printer:

• To start printing to PrintPreviewDialog:

• Both fire PrintDocument's PrintPage event

prtDocument.Print()

ppdPrintPreview.Document = prtDocument ppdPrintPreview.ShowDialog()

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 20

Setting Up the Print Output• PrintPage event is fired once per page to be printed• PrintPage event includes the argument e as

System.Drawing.Printing.PrintPageEventArgs

• Properties of the PrintPageEventArgs are used in setting up DrawingStringMethod to print a page line

Private Sub prtDocument_PrintPage(ByVal sender As Object, _ByVal e As

System.Drawing.Printing.PrintPageEventArgs) _Handles prtDocument.PrintPage

‘Code for printing lines of documentEnd Sub

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 21

DrawString Method

• Sends a line of text to the graphics page• General Form

• Examples

DrawString(StringToPrint, Font, Brush, Xcoordinate, Ycoordinate)

e.Graphics.DrawString(strLine, fntFont, Brushes.Black, sngX, sngY)e.Graphics.DrawString("My String", fntMyFnt, Brushes.Red,100.0, 100.0)e.Graphics.DrawString(txtName.Text, New Font("Arial", 10), _

Brushes.Black, sngLeftMargin, sngCurrentLine)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 22

PrintPageEventArgs and DrawString Method Arguments

• String to print• Font • Brash color• MarginBounds

– Code as• e.MarginBounds.Left

• e.MarginBounds.Right

• e.MarginBounds.Top

• e.MarginBounds.Bottom

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 23

DrawString Method: ExamplePrivate Sub prtDocument_PrintPage(ByVal sender As Object, _

ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles _

prtDocument.PrintPage 'Handle all printing and print preview.

Dim fntPrintFont As New Font("Arial", 12) Dim sngLineHeight As Single = fntPrintFont.GetHeight + 2 Dim sngPrintX As Single = e.MarginBounds.Left Dim sngPrintY As Single = e.MarginBounds.Top Dim strPrintLine As String Dim intListIndex As Integer

'Loop through the entire coffee list. For intListIndex = 0 To cboCoffee.Items.Count - 1

strPrintLine = CStr(cboCoffee.Items(intListIndex)) 'Set up a line.

e.Graphics.DrawString(strPrintLine, fntPrintFont, Brushes.Black, sngPrintX, sngPrintY)

sngPrintY += sngLineHeight ‘move to the next line NextEnd Sub

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 24

Static Variables• Local variable that retain their value for the life of

the project• Can be useful for

– Running totals

– Running counts

– Boolean switches

– Storing current page number/count when printing multiple pages

• Declaration

Static intPageCount as Integer = 1

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 25

Printing Multiple PagesPrivate Sub prtDocument_PrintPage(ByVal sender As Object, _

ByVal e As System.Drawing.Printing.PrintPageEventArgs) _ Handles prtDocument.PrintPage‘Prints multiple pages.

‘All local variables are declared made here.Static intPageConunt as Integer = 1sngPrintY = e.MarginBounds.Top

‘Printing page number code goes hereDo ‘print a line

e.Graphics.DrawString(strPrintLine, fntPrintFont, _ Brushes.Black, sngPrintX, sngPrintY)sngPrintY += sngLineHeight 'start at the next line

Loop Until sngPrintY > e.MarginBounds.Bottom

intPageCount +=1If intPageCount <=4 Then ‘restrict to 4 pages

e.HasMorePages = True ‘there are more pages to printElse

e.HasMorePages = FalseEnd If

End Sub

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.7- 26

Adding a New Form to a Project

• Select Add New Item from the Project Menu• In the dialog select Windows Form• Design and setup form as usual and give it a name

(e.g. frmAbout)• Use form’s Show method to display a new form

Private Sub mnuHelpAbout_Click(ByVal sender As Object, ByVal _ e As System.EventArgs) Handles mnuHelpAbout.Click 'Display frmAbout. Dim AboutForm As New frmAbout()

AboutForm.Show() End Sub