7-lists_loops_printing.htm; updated April 8, 2004
 

Lists, Loops, and Printing

OBJECTIVES:

·       Create/use list boxes and combo boxes.

·       Understand the available types of combo boxes.

·       Enter items into list boxes using the Items collection.

·       Add/remove items in a list at run time.

·       Determine which 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.

·       Send information to the printer or the Print Preview window using the PrintDocument class.

 

NOTE:  The program coding presented in these notes is coded with Option Strict On.


List Box, Checked List Box, and Combo Box

These three controls are standard controls available in the Visual Basic.NET Tool Box (see Figure 7.1).  They are used to store lists of values.

 

What are the advantages of using list-type controls?

Figure 7.1

 

There are several different styles of list boxes and combo boxes – Figure 7-2.

Figure 7-2

 

·       List box – you can make this any size that you want and you can pick from the list, but not type new items into the control.

·       Checked List Box – has checkboxes inside the list box.

·       Drop-down combo box – includes a text box and list box together, you can type new items into the text box portion of the control – doesn't take up much space on the form.

·       Simple combo box – you can type text into the box at the top and see part of the list and scroll up and down.

·       Drop-down list – a combo box with no textbox into which to type new items, but the text displays at the top when selected.

 

List and combo boxes automatically have vertical scroll bars added by VB when the list is too large to display all items on the form.

 

List and combo boxes have a Sorted property that will automatically sort the list at runtime.

 

List boxes always display the Name property at design time – you cannot delete it!  Combo boxes display the Text property.  At run time they will display the appropriate values so don't worry about what they display at design time.

 

The prefixes to make these controls are: lst for a list box, clb for a checked list box, and cbo for a combo box.

The Items Collection

The list of items that display in a list or combo box is called a collection.

 

Collections have properties and methods to make it easy to add items, remove items, and refer to individual items. 

 

The items in the list are numbered beginning with the number 0.  A list of 10 items has the items numbered 0 through 9. 

 

Filling the List

At design time, you can type items into a list by clicking on the Items property shown in Figure 7.3.  A String Collection Editor window will open and you simply type items for the list into the editor.

 

Use this approach if you know the items in the list and the list never changes or does not change very much.

 

Figure 7.3

 


In-Class Exercise

Start up VB. Create a form like that shown in Figure 7.4.  Name the form frmCh7InClass and set the form's Text property to Chapter 7 In Class.

Figure 7.4

 

·       Add a list box named lstFruit.  Set the Sorted property to True.

·       Use the Items property to store the five values shown in Figure 7.4 to the list box.

·       Add a combo box – set the DropDownStyle property to DropDown.  Name it cboStates. 

·       Enter the following state names: Illinois, California, Colorado, Alabama, Arizona, Alaska, and Arkansas.

·       Set the Sorted property to True.  Set the Text property to blank.

·       Run the project and note that the fruit selected from the list box is highlighted and the combo box displays the state selected.

 


Items.Add Method

The Items.Add method is used to add an item to a list or combo box at run time.  An example command to add a fruit to the list is:

 

lstFruit.Items.Add("Peach")

 

If the value to be added is stored in a textbox, the command would need to add the contents of the Text property to the list box Items collection.  The command is:

 

lstFruit.Items.Add(txtFruit.Text)

 

The Items.Add method works for combo boxes in the same fashion.

 

cboStates.Items.Add("Wyoming")

 

cboStates.Items.Add(txtState.Text)

 

When a new item is typed into the Text portion of a combo box, you must execute code to add the item to the Items collection for the combo box.

 

cboStates.Items.Add(cboStates.Text)

 


In-Class Exercise

Modify the form to add a button control and a text box – see Figure 7.5.

Figure 7.5

 

·       Name the button btnAdd and set the Text property to Add Fruit.

·       Name the textbox txtFruit and set the Text property to blank.

·       Add code to use the Items.Add method to add the Text property value of txtFruit to lstFruit when btnAddFruit is clicked, but not if the Text property is blank. 

 

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

    'Add text box value to fruit listing

    If txtFruit.Text = "" Then  'Textbox is empty

        MessageBox.Show("Enter a fruit to add.", "Data Error",  MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

       txtFruit.Focus()

    Else

        'OK to add the item to the list

        lstFruit.Items.Add(txtFruit.Text)

    End If

End Sub

 

The above code fails if the textbox contains spaces.  Additionally, the value "  Apple  " with spaces either before or after the fruit name will result in adding another Apple to the listing.

 

This error can be eliminated by trimming any leading/trailing blanks from the value in the txtFruit textbox through use of a Trim() function or .Trim method.  The modified code is shown here.

 

Private Sub btnAddFruit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddFruit.Click

    'Add text box value to fruit listing

    If Trim(txtFruit.Text) = "" Then  'Textbox is empty

        MessageBox.Show("Enter a fruit to add.", "Data Error",  MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

       txtFruit.Focus()

    Else

        'OK to add the item to the list

        lstFruit.Items.Add(Trim(txtFruit.Text))

    End If

End Sub

 

Equivalent code using the .Trim method.

 

Private Sub btnAddFruit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddFruit.Click

    'Add text box value to fruit listing

    If txtFruit.Text.Trim = "" Then  'Textbox is empty

        MessageBox.Show("Enter a fruit to add.", "Data Error",  MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

       txtFruit.Focus()

    Else

        'OK to add the item to the list

        lstFruit.Items.Add(txtFruit.Text.Trim)

    End If

End Sub

 

 

You may also note that this code does not handle the insertion of duplicate fruit items – you will learn to write code to prevent this error later in this chapter.

 


Items.Insert Method

If you do not sort the list, you can use the Items.Insert method to specify exactly where within a collection to add a new item.  You do this by specifying the number position, also called the index position of the new item.

 

This will add Grape as the very first item in the list.  However, if the Sorted property is True, then specifying the location will not have any effect.

 

lstFruit.Items.Insert(0,"Grape")

 

Items.Clear Method

The Items.Clear method will remove the contents of a list or combo box. 

 

lstFruit.Items.Clear()

 

SelectedIndex Property

When a system user selects an item from a list, the index number associated with the item is stored to the SelectedIndex property.

 

When no item is selected, SelectedIndex equals -1.

 

You can select an item from a list by storing a numeric value to the SelectedIndex property.

 

lstFruit.SelectedIndex = 3  'Selects the 4th fruit item

cboStates.SelectedIndex = 2 'Selects the third state

lstFruit.SelectedIndex = -1 'Unselects the list items

SelectedItem Property

When a system user selects an item from a list, the item selected is stored to the SelectedItem property.  This property can be used to display the selection elsewhere, for example, in a label control.

 

'Displays the selected item from the listbox

'to a label named lblFruit

lblFruit.Text = lstFruit.SelectedItem.ToString() 

 

Items.Count Property

The Items.Count property stores a number equal to the number of items in a list or combo box Items collection.

 

The value of Items.Count is always 1 more than the maximum allowable SelectedIndex value.  If there are 5 items in a list, then SelectedIndex possible values are 0 through 4, but Items.Count equals 5.

 

Use this property to display the number of items in a list.

 

MessageBox.Show("Number of States: " & cboStates.Items.Count.ToString())

Referencing the Items Collection

To display an item in a list to another control, such as a textbox named txtFruit, the command is:

 

'Displays first item to the textbox

txtFruit.Text = lstFruit.Items(0).ToString() 

 

Note:  The value from the listbox must be converted to string using either the ToString method or the CStr() function because the listbox is a system.object and a Text property can only store a string value when Option Strict On is applied.

 

If a system user selects an item on a list and you want to display the selected item to another control such as a textbox, the command is:

 

'Display selected fruit item to textbox

txtFruit.Text = lstFruit.Items(lstFruit.SelectedIndex).ToString

 

'Display selected state to a textbox

txtState.Text = cboStates.Items(cboStates.SelectedIndex).ToString

 

Items.RemoveAt and Items.Remove Method

To remove an individual item from a list, specify either the index or text of the item. 

·       The Items.RemoveAt method removes an item by specifying the index position.

·       The Items.Remove method removes an item by specifying the item name.

 

'Removes the first item from the list

lstFruit.Items.RemoveAt(0)

 

'Removes the item according to the value of intIndex

lstFruit.Items.RemoveAt(intIndex)

 

'Remove the currently selected item

cboStates.Items.RemoveAt(cboStates.SelectedIndex)

 

'Remove item by name where the item name is stored to a textbox

lstFruit.Items.Remove(txtFruit.Text)

 


In-Class Exercise

·       Add buttons as shown in Figure 7.6.  Name them btnDisplay, btnRemove and btnClear with Text properties as shown.

Figure 7.6

 

·       When btnDisplay is clicked, display the selected fruit item to the txtFruit textbox.  Use a Try/Catch block to display an error message if no fruit item has been selected from the list box.

 

Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click

    'Display fruit to textbox

    Try

        txtFruit.Text = lstFruit.Items(lstFruit.SelectedIndex).ToString

    Catch

        MessageBox.Show("Select a Fruit", "Data Error",  MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    End Try

End Sub

 

·       When btnRemove is clicked, remove the currently selected lstFruit list box item with the RemoveAt method.  Use a Try/Catch block to catch the error that occurs if no fruit is selected. 

 

Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click

    'Remove selected fruit from the list box

    Try

        lstFruit.Items.RemoveAt(lstFruit.SelectedIndex)

    Catch

        MessageBox.Show("Select a Fruit", "Data Error", _

            MessageBoxButtons.OK, _

            MessageBoxIcon.Exclamation)

    End Try

End Sub

 

·       When btnClear is clicked, clear the lstFruit list box of all items.

 

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click

    'Clear the fruit list box

    lstFruit.Items.Clear()

End Sub

 

 


List Box and Combo Box Events

Code can be written for several events of list boxes and combo boxes.  These include:

·       SelectedIndexChanged Event.  Occurs when a system user makes a new selection for a list or combo box.

·       TextChanged Event.  As a system user types characters into the text box portion of a combo box, this event is triggered for each character typed.  List boxes do not have this event.

·       Enter Event.  When a list or combo box receives focus, this event occurs. 

·       Leave Event.  When a list or combo box loses focus, this event occurs. 

 


In-Class Exercise

 

In the object drop-down combo box, select cboStates combo box as shown in Figure 7.7.  Next select the Leave event from the property, method and event drop-down combo box.

Figure 7.7

 

·       Code the Leave event to add the value that is typed into the Text property of cboStates to the Items collection of cboStates. 

 

Private Sub cboStates_Leave(ByVal sender As Object, _

    ByVal e As System.EventArgs) Handles cboStates.Leave

    'Store combo box Text property value to Items collection

    cboStates.Items.Add(cboStates.Text)

 

    'Remove the State name displayed in the Text property

    'of the combo box

    cboStates.Text = ""

End Sub

 

·       Note that this code enables adding duplicate values as well as blank values.  Later you will learn how to prevent this from happening.

 


Loops

Loop structures enable you to execute a series of commands over and over.  An iteration is a single execution of the loop.   There are two types of loops:

·       Condition-controlled.  These loops execute over and over until a specific condition occurs.  In VB.NET, these are Do Loops.

·       Count-controlled.  These loops execute for a specified number of times.  In VB.NET, these are For-Next Loops.

The Boolean Data Type

A Boolean variable has a value of either True or False.

 

We often use a Boolean to control the stopping condition for a loop.  The default value for a Boolean when you declare the variable is False.  An example of declaring a Boolean is:

 

Dim blnFound as Boolean

Do Loops

Do Loops can execute the coding statements within the body of the loop either:

·       until a condition is met that causes the loop to terminate (stop executing),

·       while a condition is met that causes a loop to continue executing.

 

Do Loops can have the condition test (we may term this the stopping condition) at either the top or bottom of a loop, and can use either a While or Until option to test the condition.

 

Condition at Top of Loop.  The following loop executes while the stopping condition blnValue is False

 

blnFound = False

Do While blnFound = False

    'Coding statements to execute.

    'Code to search for some value

    If ValueIsFound = True Then

        blnFound = True

    End If

    intIndex += 1

Loop

'Control transfers here after the loop finishes.

 

This loop works like the one above, but uses Until logic.  The loop executes until the stopping condition blnFound is True.  These are the mirror image of each other.  Use the approach that you like best.

 

blnFound = False

Do Until blnFound = True

    'Coding statements to execute.

    'Code to search for some value

    If ValueIsFound = True Then

        blnFound = True

    End If

    intIndex += 1

Loop

'Control transfers here after the loop finishes.

 

Condition at Bottom of Loop.  This next loop will always execute the body of the loop at least one time because the stopping condition is not tested until the end of the loop.

blnFound = False

Do

    'Coding statements to execute.

    'Code to search for some value

    If ValueIsFound = True Then

        blnFound = True

    End If

    intIndex += 1

Loop While blnFound = False

'Control transfers here after the loop finishes.

 

You can also test for an Until condition at the bottom of a Do Loop.

 

Searching a List or Combo Box                          

As was noted earlier, one of the problems with the btnAdd_Click event for lstFruit is that you can add duplicate fruit values.  This is also true for the cboStates combo box.

 

Likewise the value APPLE is different than Apple so this would also result in adding the value to the list, even though to a system user an APPLE is the same thing as an Apple.

 

In order to fix this problem, you need to be able to search the items in the Items collection of the list or combo box to determine whether or not the item is already in the collection.  Additionally, the .ToUpper method can be used to treat the values in both the lstFruit listbox and txtFruit textbox as if the values  were typed in capital letters.

 

Logically, we will assume that the item to be added is NOT in the collection by setting a Boolean variable blnFound to a value of False. 

 

A Do Loop is used to examine each item in the Items collection starting at item 0 until there are no more items. 

·       If the item is found to match the value in the textbox, then blnFound is set to True and the search terminates.

·       If the item is never found the item index variable intIndex will eventually grow in value until it equals lstFruit.Items.Count, it is added to the collection.

·       Note:  Notice the use of multiple methods ToString, Trim, and ToUpper with the lstFruit listbox to convert the value to a string, trim off any leading/trailing blank spaces, and treat the value as if it were entered in all capital letters.

 

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

  'Add text box value to fruit listing

  Dim blnFound As Boolean = False

  Dim intIndex As Integer = 0

 

  Do Until blnFound = True Or _

        intIndex = lstFruit.Items.Count

      If txtFruit.Text.Trim.ToUpper = _

            lstFruit.Items(intIndex).ToString.Trim.ToUpper Then

          blnFound = True

      End If

      intIndex += 1   'Add 1 to index value

  Loop  'Loop back and try again

 

  'Now decide whether to add item or not

  If blnFound = False And txtFruit.Text <> "" Then

        lstFruit.Items.Add(txtFruit.Text.Trim)

  Else

      MessageBox.Show("Duplicate or Invalid Fruit Item", "Data Error",  MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

      txtFruit.Focus()

      txtFruit.SelectAll()

  End If

End Sub

 


In-Class Exercise

·       Replace the code for the btnAdd button's click event with the code shown above. 

·       Run the project and test the system by adding a new fruit and by adding a duplicate fruit.


For/Next Loops

A For/Next loop is a count-controlled loop - it always executes a set number of times based on a loop index.

 

Example For/Next loop: 

 

Dim intCount As Integer

For intCount = 1 To 5 Step 2

    lblCount.Text = intCount.ToString

    'Print some output so you can see the

    'loop counting as it loops around.

    lstCount.Items.Add(intCount.ToString)

Next intCount

'Control transfers to here when the loop ends

 

A loop index is an numeric variable (usually integer or single) used to control For/Next loops.  The loop index above is the variable intCount.

 

The loop index is initialized to a starting value.  The starting value above is 1.

 

After each execution of the loop, the loop index is changed (made larger or smaller) by the step value.  The step value above is 2.  The Step value need not be specified - if it is not specified, it is automatically assumed to be 1.

 

The loop is terminated when the loop index exceeds the ending value.  The ending value above is 5.

 

Other example For/Next statements.

 

For intIndex = 2 To 100 Step 4

 

For intCount = intStart To intEndValue Step intIncrement

 

For intIndex = 0 to (cboStates.Items.Count -1)

 

For decorate = 0.05D To 0.25D Step 0.05D

 

For intIndexBackwards = 10 To 0 Step -1

 

 


In-Class Exercise

Example--Counting Forward

·       Add a label to your form named lblCount, and a button named btnCount.  Add a list box named lstCount.

·       Attach this code to the button's click event.

 

Dim intCount As Integer

For intCount = 1 To 5 Step 2

    lblCount.Text = intCount.ToString

    'Print some output so you can see the

    'loop counting as it loops around.

    lstCount.Items.Add(intCount.ToString)

 

Next intCount

'Control transfers to here when the loop ends

 


 


Counting Backward

This loop counts backwards from 10 to 1 by 1, e.g. 10, 9, 8, ... 2, 1. The loop stops when intCount is less than 1.

 

For intCount = 10 To 1 Step -1

    lblCount.Text = intCount

    'Print some output so you can see the

    'loop counting as it loops around.

    lstCount.Items.Add(intCount.ToString)

Next intCount

 

A Loop That Will Not Execute

A loop condition is always checked the first time that a For-Next statement executes.  In this example, intIndex is already larger than the ending value for the loop (intFinalValue).

 

intFinalValue = 5

For intIndex = 6 to intFinalValue

    'Nothing happens – the final value is less than

    'the starting value

Next intIndex

 

Altering Loop Control Variable Values

Once a For-Next loop begins to execute, the values of starting value, ending value, and step increment are set – changing these values within the loop CAN affect execution of the loop.  You can change the loop index, but this practice is poor – it would be difficult to find a situation where it would be necessary.

Nested Loops – A Loop Inside a Loop

This example shows a For/Next loop inside another For/Next loop.  The inner loop must be completely contained within the outer loop.  The inner loop executes a "normal number" of times for each execution of the outer loop.

 

Dim lngTotal As Long

Dim intOuterIndex As Integer

Dim intInnerIndex As Integer

lngTotal = 0

'Start of the outer loop.

For intOuterIndex = 1 To 10

    'Start of the inner loop – each time we get here the

    'inner loop starts all over again

    For intInnerIndex = 1 To 10

        lngTotal += 1

        lstCount.Items.Add(lngTotal.ToString)

    Next intInnerIndex

    'Exited inner loop – control transfers to outer loop

Next intOuterIndex

'Control transfers here when the outer loop ends

 

Exit For Statement

The Exit For statement is used to exit a For-Next loop before the ending value is reached.  Example:

 

For intLoopIndex = 1 To 10

    If txtInput.Text = "" Then 'Blank input

        MessageBox.Show("Input is invalid")

        Exit For

    End If

    'Other statements to process if the input is valid

Next intLoopIndex

 


Selecting Control Entries

Selecting a Text Box Entry

If a text box already has data when a system user tabs to a text box, you can put the insertion point at the left or right end of the text.  You can also highlight the entire entry to make it appear selected.  You would do the latter if the data entered fails a validation test and must be reentered.

 

The text box Enter event combined with the SelectAll method will highlight text.

 

Private Sub txtFruit_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFruit.Enter

    'Select existing text values

    txtFruit.SelectAll()

End Sub

 

Selecting a List or Combo Box Entry

You can also highlight text in a list or combo box.  We've seen this already.  Simply store the value of the desired item to the SelectedIndex property of the list or combo box.

 

lstFruit.SelectedIndex = intIndex

 

The sub procedure shown next uses the TextChanged event for the txtFruit text box to search for values in lstFruit as characters are typed into the Text portion of the text box control.

 

Private Sub txtFruit_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFruit.TextChanged

    'Locate matching value

    Dim intIndex As Integer = 0

    Dim blnFound As Boolean = False

    Dim strListItem As String

 

    Do While Not blnFound And intIndex < lstFruit.Items.Count

        'Store the value of the first collection tem to

        'the a string variable

        strListItem = lstFruit.Items(intIndex).ToString.ToUpper

 

        'Now compare the values

        If strListItem.StartsWith(txtFruit.Text.ToUpper) Then 

            'Found a fruit that starts with the value.

            'Select that item in the list box

            lstFruit.SelectedIndex = intIndex

            blnFound = True

        End If

        intIndex += 1

    Loop

End Sub

 

 


In-Class Exercise

Selecting a Text Box Entry

·       Use the code shown above to test your ability to highlight text in the txtFruit textbox. 

·       After entering the code, enter a value in the text box, then tab around the form until the text box is again selected – it should highlight the text in the control.

Selecting a List or Combo Box Entry

·       Use the code shown above to search for a value typed into txtFruit in the lstFruit list box.

·       Enter the following values into the lstFruit before testing the code – B, Ba, Ban, Bana, and Banan.  Test the code.

 


PRINTING

Printing Approaches

Most printing is done by using a separate utility program.  Crystal Reports is one such program and is used to produce reports for program that interact with databases.

 

For this reason, we will not spend a lot of time on printing using built-in VB capabilities because the Crystal Reports utility is shipped as part of the VB Professional and Enterprise editions.

 

The PrintDocument Control

The PrintDocument control provides methods and events to print in VB.  Add the control to the project and it appears in the component tray.

 

The prefix is "prt" for naming the control, e.g., prtDocument.

 

The Print method of the PrintDocument control starts producing printed output.

 

prtDocument.Print() 'Starts printing

 

The PrintPage event stores the logic for printing.  This event fires once for each page to be printed.  When you execute a Print method, this activates the PrintDocument object and this then fires the PrintPage event.

 

Basically, the program sets up a graphics page in memory, and then the page is sent to the printer.  The graphics page contains strings of text and graphics elements.

 

Each element to be printed is specified by X and Y coordinates:

·       X is the horizontal distance across a line from the left edge.

·       Y is the vertical distance down a page from the top edge.

·       All measurements are in pixels.

·       Use variables to specify X and Y and declare the variables as single data type.

 

Example:

Dim sngX As Single

Dim sngY As Single

sngX = e.MarginBounds.Left 'Initialize sngX

sngY = e.MarginBounds.Top  'Initialize sngY

 

The DrawString method sends a line of text to the graphics page.  The general form is:

 

DrawString(StringToPrint, Font, _

    Brush, Xcoordinate, Ycoordinate)

 

Example:

 

e.Graphics.DrawString("My Report", fntMyFont, _

    Brushes.Black, 100.0, 100.0)

 


In-Class Exercise

Printing List Box Contents

We will study the code used to print a simple report that has a heading detail lines by printing the contents of the cboStates combo box. 

·       Add a button to the form named btnPrint. 

·       Add a PrintDocument control to the form and name it prtDocument.

·       Access the click event for btnPrint and add the code shown here.

 

Private Sub btnPrint_Click(ByVal sender As System.Object, _

    ByVal e As System.EventArgs) Handles btnPrint.Click

    'Begin printing by calling Print method

    prtDocument.Print()

End Sub

 

Calling the Print method will trigger the PrintPage event of the PrintDocument control. 

·       Use the class name drop down list box in the coding window and select the prtDocument object, then select the PrintPage method to open up a sub procedure named prtDocument_PrintPage. 

·       Add the code shown here to the sub procedure.  Notice the code highlighted in red – here e is a parameter object passed to the sub procedure as an instance of the System.Drawing.Print.PrintPageEventArgs object.  Likewise e.MarginBounds.Left and e.Graphics.DrawString are properties and methods of the object.

 

Private Sub prtDocument_PrintPage(ByVal sender As Object, _

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

    Handles prtDocument.PrintPage

    'Handle all printing tasks

 

    'Declare variables and fonts

    'Declare the fonts for the heading and detail lines

    Dim fntPrintFont As New Font("Arial", 12)

    Dim fntHeading As New Font("Arial", 14, FontStyle.Bold)

 

    'Declare line height and sngX and sngY variables

    'The GetHeight method gets the height of the selected

    'Font – add 2 pixels to this height for spacing

    Dim sngLineHeight As Single = fntPrintFont.GetHeight + 2

   

    'Set the sngX and sngY coordinate variables to the

    'current left and top margins 

    Dim sngX As Single = e.MarginBounds.Left

    Dim sngY As Single = e.MarginBounds.Top

 

    'Declare print line string variable and index to

    'access the combo box

    Dim strPrintLine As String

    Dim intIndex As Integer

 

    'Print the heading

    strPrintLine = "List of States"

    e.Graphics.DrawString(strPrintLine, fntHeading, _

        Brushes.Black, sngX, sngY)

   

    'Add to Y position for the next line

    sngY += sngLineHeight

 

    'Print the detail lines in a loop -- each line is

    'one state listing -- print until no more items

    Do While intIndex < cboStates.Items.Count

        'Set up line to print

        strPrintLine = "   " & _

            CStr(cboStates.Items(intIndex))

        'Send line to graphics page

        e.Graphics.DrawString(strPrintLine, fntPrintFont, _

            Brushes.Black, sngX, sngY)

        'Add to Y position for next line

        sngY += sngLineHeight

        'Add 1 to intIndex

        intIndex += 1

    Loop

End Sub


Aligning Decimal Columns (This section is not covered on your Examination)

Numeric data with decimal points must be aligned when printed.  This requires the use of an object declared as a SizeF structure.  Structures are covered later in the course.  For now we will just use the Width property of a SizeF structure and the MeasureString method, which measures the width in pixels to help align columns.

 

This code prints a literal that is left-justified at pixel position 200.  It prints a formatted number that is right-justified (aligned) at position 500.  Assume that all variables are already declared.

 

Dim stzStringSize As New SizeF()  'SizeF structure

 

'Set X for left-aligned output

sngX = 200F

 

'Set ending position for right-aligned column

sngColumnEnd = 500F

 

'Format number stored in decAmount variable

strFormattedOutput = FormatCurrency(decAmount)

 

'Calculate X position for the amount

stzStringSize = e.Graphics.MeasureString(strFormattedOutput, _

    fntPrintFont)

 

'Subtract the width of the string from the column position

sngX = sngColumnEnd – stzStringSize.Width

 

'set up lines

e.Graphics.DrawString("The Amount is: ", fntPrintFont, _

    Brushes.Black, sngX, sngY)

e.Graphics.DrawString(strFormattedOutput, fntPrintFont, _

    Brushes.Black, sngX, sngY)

sngY += sngLineHeight  'Increment for next line

 


Print Preview

Print Preview allows you to see the output that will print before printing.  You can then choose to print or cancel.  This keeps you from wasting paper during debugging.

 

The PrintPreviewDialog control must be added to the form's component tray.  I usually name the control ppdPreview. 

 

The PrintPreviewDialog class uses the same PrintDocument control by assigning the PrintDocument to the Document property of the PrintPreviewDialog control and use the ShowDialog method to show the control. 

 

The same PrintPage event procedure will execute as was used for the PrintDocument control. 

 

Assume a button named btnPrintPreview.  The click event code is:

 

Private Sub btnPreview_Click(ByVal sender As System.Object, _

    ByVal e As System.EventArgs) Handles btnPreview.Click

    'Print preview

    ppdPreview.Document = prtDocument

    ppdPreview.ShowDialog()

End Sub

 

Figure 7.8 shows the Print Preview form that is displayed by the ShowDialog method. 

Figure 7.8

 


In-Class Exercise

Printing a Preview of the List Box Contents

·       Add a button named btnPreview. 

·       Add a PrintPreviewDialog control to the form's component tray and name it ppdPreview

·       Add the code for the click event of the ppdPreview control shown above and test the project.

 



END OF NOTES