Vous êtes sur la page 1sur 8

7/31/2014

Objectives (1 of 2)

Chapter 7

Lists, Loops, and


Printing

McGraw-Hill

7-2

Copyr ight 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

Filling a List Design Time

Objectives (2 of 2)

Create and use list boxes and combo boxes.


Differentiate among the available types of combo
boxes.
Enter items into list boxes using the Items
collection in the Properties w indow.
Add and remove items in a list at run time.
Determine w hich item in a list is selected.
Use the Items.Count property to determine the
number of items in a list.

Display a selected item from a list.


Use Do/Loops and For/Next statements to iterate
through a loop.
Terminate a loop w ith the Exit statement.
Skip to the next iteration of a loop by using the
Continue statement.
Send information to the printer or the Print Preview
w indow using the PrintDocument class.

Click ellipses button to open

7-3

ListBoxes and ComboBoxes (1 of 2)

7-4

List Boxes and Combo Boxes (2 of2)

Have most of the same properties and operate in a


similar fashion
An exception is that a combo box control has
a DropDow nStyle property
Provide the user w ith a list of items to select from
Various styles choose based on
Space available
Need to select from an existing list
Need to add to a list

Various Sty les of List and Combo boxes


7-5

7-6

7/31/2014

Filling a List/Using the Properties Window

The Items Collection

List of items in a ListBox or ComboBox is a


collection.
VB Collections are objects that have properties
and methods that allow

Adding items
Remov ing items
Ref erring to individual elements
Counting items
Clearing the collection

Design time in Properties w indow

Run time methods

Items property
Click on ellipses to open String
Collection Editor.
Ty pe list items, end each line with
Enter key .

Items.Add

Items.Insert

--OR--

7-7

7-8

Using the Items.Insert Method

Using the Items.Add Method

Use to add new items to the list at run time.


General Form

Examples

Object.Items.Add(ItemValue)

Use to add new items to the list at run time in a


specific location (index position) in the
collection.
General Form
Object.Items.Insert(IndexPosition, ItemValue)

Examples

SchoolsListBox.Items.Add("Harvard")
SchoolsListBox.Items.Add("Stanford")
SchoolsListBox.Items.Add(SchoolsTextBox.Text)
MajorsComboBox.Items.Add(MajorsComboBox.Text)
MajorsComboBox.Items.Add(MajorString)

SchoolsListBox.Items.Insert(0, "Harvard")
MajorsComboBox.Items.Insert(1, MajorsComboBox.Text)

7-9

7-10

The Items.Count Property

The SelectedIndex Property

Index number of currently selected item is stored in


the SelectedIndex property.
If no list item is selected, SelectedIndex property is
negative 1 (-1).
Use (w ith value 0 to Count 1) to select an item in list
or (w ith -1) deselect all items in code.

to determine number of items in the list

Remember:
Items.Count is always one more than the highest
possible SelectedIndex, because indexes begin with 0
For example, if there are five items in a list:
Items.Count = 5
AND
Highest Index = 4

7-11

7-12

7/31/2014

Removing an Item from a List

Referencing the Items Collection

Use the index of the item to reference a specific


item in the collection.
Remember that the index is zero based, so the first
item in the list is index position zero.
SchoolsListBox.Items(5) = "University of California"
MajorLabel.Text = MajorsComboBox.Items(IndexInteger)
SelectedMajorLabel.Text =
MajorsComboBox.Items(MajorsComboBox.SelectedIndex)
SelectedMajorLabel.Text = MajorsComboBox.Text

Use the Items.RemoveAt method to remove an


item by index from the list and the
Items.Remove method to remove by specifying
the text.
General Form Object.Items.RemoveAt(IndexPosition)

Examples

NamesListBox.Items.RemoveAt(0)
' Remov e the item in position IndexInteger.
SchoolsComboBox.Items.RemoveAt(IndexInt
eger)
Cof feeComboBox.Items.RemoveAt(CoffeeCo
mboBox.SelectedIndex)

7-13

7-14

The Items.Remove Method

Use the Items.Remove method to remove an item by


specifying the text.
General Form Object.Items.Remove(TextString)

Examples

Clearing a List

Use the Items.Clear method to clear all items and


empty a combo box or list box.
General Form Object.Items.Clear( )

Examples

NamesListBox.Items.Remove("My School ")


SchoolsComboBox.Items.Remove(SchoolTextBox.Text)
' Next line removes the currently selected item.
CoffeeComboBox.Items.Remove(Co ffeeComboBox.Text)

SchoolsListBox.Items.Clear( )
MajorsComboBox.Items.Clear( )

7-15

7-16

List Box and Combo Box Events

Do/Loops

In the Editor window, select the control name in the Class Name
list (at the top-left of the window), drop down the Method Name list, and
select the event for which you want to write code or double-click the
event name in the Properties window after clicking the Events button.
The Editor will create the procedure header for you.
TextChanged Event
Occurs when user types text into combo box
List box does not have TextChanged Event.
Enter Event (control receives focus) an Enter event fires when a user
tabs from control to control.
Leave Event (control loses focus) a Leave event triggers as user tabs
between controls.

A loop repeats a series of instructions.


An iteration is a single execution of the statement(s) in
the loop.
Used when the exact number of iterations is unknown
A Do/Loop terminates based on a specified condition.

Execution of the loop continues while a condition is


True or until a condition is True.

The condition can be placed at the top (pretest)or the


bottom (posttest) of the loop.

7-17

7-18

7/31/2014

The Do and Loop Statements General


Form
Do {While |Until} condition
' Statements in loop.
Loop

Pretest vs. Posttest

Top of Loop
Condition,
P retest/Entry
test

--OR-Do

' Statements in loop.


Loop {While | Until} condition

Bottom of
Loop
Condition,
P osttest/ Exit

Pretest loop may never be executed since


tested BEFORE running.
Do While Loop
Do Until Loop
Posttest loop w ill alw ays be executed at least
once.
Do Loop While
Do Loop Until

7-19

7-20

The Boolean Data Type Revisited

Pretest vs. Posttest Diagram

Can help w hen searching a list for a specific value


Boolean variable is alw ays in one of tw o states: True
or False.

When a particular situation occurs, set Boolean v ariable to


True.

Use a loop to check f or True


Many programmers refer to Boolean variables as
sw itches or flags.

Switches hav e two states on or off.


Flags are considered either up or down.

7-21

The For and Next Statements General


Form

For/Next Loops

7-22

Used to repeat statements in a loop a specific


number of times
Uses a numeric counter variable, called Loop Index,
w hich is tested to determine the number of times the
statements inside the loop w ill execute
Loop Index is incremented at the bottom of the loop
on each iteration.
Step value can be included to specify the
incrementing amount to increment Loop Index, step
can be a negative number.

For LoopIndex [As DataType] = InitialValue To TestValue


[Step Increment]
' Statements in loop.
Next [LoopIndex]
A For/Next loop can handle all three elements of a countercontrolled loop.
Initialize the counter.
Increment the counter.

Test the counter to determine when it is time to


terminate the loop.
7-23

7-24

7/31/2014

For/Next Loop Diagram

Exiting Loops

In some situations, you may need to exit the loop


prematurely.
Click on the forms close box or use the VB menu bar
or toolbar to stop the program; or Ctrl+Break.
Use the Exit For statement inside the loop structure.
Generally, the Exit For statement is part of an If
statement.

7-25

7-26

Making Entries Appear Selected

Sending Information to the Printer

When a user tabs into a text box that already has an


entry, the user-friendly approach is to select the text.
If a text box fails validation, select the text.
Selecting the entry in a Text Box

Use the SelectAll method


Good location is in the text boxs Enter event

Selecting an entry in a List Box

Set the SelectedIndex property to make a single item in a


list box appear selected.

Components appear in the Printing tab of the toolbox.


Most professional programmers use a separate utility
program to format printer reports.
Several companies sell utilities that do a nice job designing
and printing reports.

VB Professional Edition and Enterprise Edition include


Crystal Reports for creating reports from database files.

7-27

7-28

The PrintDocument Component

Setting Up the Print Output

Appears in the
Component Tray
Execute the Print method
to start printing.
The code belongs in the
Click event procedure for
the Print button or menu
item that can be selected
to begin printing.

7-29

PrintPage event is fired once for each page to be


printed, and is referred to as a callback.
BeginPrint and EndPrint are also fired at the
beginning and end of the printing.
PrintPage event includes the argument e as
System.Draw ing.Printing.PrintPageEventArgs.
Properties of the PrintPageEventArgs are useful for
handling page margins and sending strings of text
to the page.

7-30

7/31/2014

The Graphics Page

Using the DrawString Method

Set up graphics page in


memory and then the page
is sent to the printer.
Can contain strings of text
and graphic elements
Specify the exact X and Y
coordinates of each
element to be printed on X coordinate is the horizontal
distance f rom across the
the page.

page; the Y coordinate is the


v ertical distance from the top
of the page.

Used to send a line of text to the graphics page


Belongs to the Graphics object of the
PrintPageEventArgs argument
Is an overloaded method so there are several
forms for calling the method
Arguments for the Draw String method include:

What to print
What f ont and color to print in
Where to print

Set up the Font and X/Y coordinates to be used


before executing the Draw String method.

7-31

7-32

Setting the X and Y Coordinates

The DrawString Method


General Form

DrawString(StringToP rint, Font, Brush, Xcoordinate, Ycoordinate)

Examples
e.Graphics.DrawString(PrintLineString, PrintFont, Brushes.Black, _
HorizontalPrintLocationSingle, VerticalPrintLocationSingle)
e.Graphics.DrawString("My text string", MyFont, Brushes.Black, _
100.0, 100.0)
e.Graphics.DrawString(NameTextBox.Text, New Font("Arial", 10), _

For each print line, specify X and Y coordinates.


Create variables declared as Single data type to
set the X and Y values.
Dim HorizontalP rintLocationSingle As Single
Dim VerticalP rintLocationSingle As Single

Brushes.Red, LeftMarginSingle, CurrentLineSingle)

7-33

7-34

PrintPageEventArgs

Printing the Contents of a List Box

PrintPageEventArgs argument has several useful


properties that are used to determine the present
settings.
MarginBounds
PageBounds
PageSettings

7-35

Techniques for printing, a loop, and the list box


properties can be combined to send the contents of a
list box to the printer
Use the Items.Count property as the number of
iterations to make.
Items collection allow s printing out the actual values
from the list.

7-36

7/31/2014

Aligning Decimal Columns


Code Example (1 of 2)

Aligning Decimal Columns

It is important to align the decimal points of numeric


data.
Proportional fonts make aligning decimal points tricky.
Format each number to be printed and measure the
length of the formatted string.
Declare an object as a SizeF Structure which has a
Width property.
Use MeasureString method of the Graphics class to
determine the width of a formatted string in pixels.

' SizeF structure for font size info.


Dim FontSizeF As New SizeF( )
' Set X for left-aligned column.
HorizontalP rintLocationSingle = 200
' Set ending position for right-aligned column.
ColumnEndSingle = 500
' Format the number.
FormattedOutputString= AmountDecimal.ToString("C")
' Calculate the X position of the amount.
' Measure string in this font.
FontSizeF= e.Graphics.MeasureString(formattedOutputString, _
P rintFont)
7-37

Aligning Decimal Columns


Code Example (2 of 2)

7-38

Displaying a Print Preview

' SizeF structure for font size info (cont).


' Subtract width of string from the column position.
ColumnXSingle = ColumnEndSingle - FontSizeF.Width
' Set up the line--each element separately.
e.Graphics.DrawString("The Amount = ", P rintFont, _
Brushes.Black, HorizontalP rintLocationSingle, _
VerticalP rintLocationSingle)
e.Graphics.DrawString(FormattedOutputString, printFont, _
Brushes.Black, ColumnXSingle, VerticalP rintLocationSingle)
' Increment line for next line.
VerticalP rintLocationSingle += LineHeightSingle

The PrintPreview Dialog component is the key to


print preview .
Add PrintPreviewDialog component to form.

Appears in the Component Tray


Def ault name is fine

Assign in code the same PrintDocum ent object


you are using for printing.
Execute the Show Dialog method of the
PrintPreviewDialog component.

7-39

7-40

PrintPreviewDialog Component

The Using Block

System resources such as fonts can be access


inside a Using block.
Variables that are declared in a Using block are
only accessible within that block.
The advantage of declaring a variable inside a
Using block is that system resources are released
as soon as the block terminates.
Using HeadingFont as New Font("Arial", 14, FontStyle.Bold
e.Graphics.DrawString(Flavors, HeadingFont, Brushes.Black,
HorizontalPrintLocationSingle, VerticalPrintlocationSingle)
End Using

7-41

7-42

7/31/2014

Printing Multiple Pages

Using Static Variables in Printing

The PrintDocuments PrintPage event fires once


for each page.
Set the HasMorePages property of the
PrintPageEventArgs argument to True to print
more than one page.

Static local variables 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

7-43

7-44

Vous aimerez peut-être aussi