Chapter 7 · Chapter 7 Lists, Loops, and ... –Determines whether list box has a text box for user...
Transcript of Chapter 7 · Chapter 7 Lists, Loops, and ... –Determines whether list box has a text box for user...
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved.
Chapter 7
Lists, Loops, and Printing
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-2
Chapter Objectives - 1
• 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 window
• Add and remove items in a list at run time
• Determine which item in a list is selected
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-3
Chapter Objectives - 2
• Use the Items.Count property to determine the
number of items in a list
• Display a selected item from a list
• Use do, while, and for loops to execute a series
of statements
• Skip to the next iteration of a loop by using the
continue statement
• Send information to the printer or the Print
Preview window using the PrintDocument class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-4
List Boxes and Combo Boxes - 1
• List boxes and combo boxes
– Have most of the same properties and
operate in a similar fashion
• One exception is that a combo box control has a
DropDownStyle property
– Determines whether list box has a text box for user entry
and if the list will drop down
– Provide the user with a list of items from
which to select
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-5
List Boxes and Combo Boxes - 2
• Various styles, choose according to space available and how the box operates – Simple list box or drop-down list
• ComboBox DropDownStyle = DropDownList
– Type a new entry to the list
• Drop-down combo box DropDownStyle = Drop-Down
• Simple combo box DropDownStyle = Simple
– Combo boxes have a Text property • Set or remove at design time
– List boxes have a Text property • Access it only at run time
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-6
List Boxes and Combo Boxes - 3
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-7
The Items Collection - 1
• The list of items in a list box or combo box
• Collections are objects that have
properties and methods that allow
– Adding items
– Removing items
– Referring to individual elements
– Counting items
– Clearing the collection
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-8
The Items Collection - 2
• Can refer to the individual items in a
collection by an index
– Zero based
– For a collection of ten items, the indexes
range from 0 to 9
– To refer to the first item in the Items collection
use Items[0]
• Notice the square brackets
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-9
Filling a List
• Several methods to fill the Items collection
of a list box or combo box
– Fill the list at design time if the list is known
and the list never changes
• Define the Items collection in the Properties
window
– Fill the list during program execution
• Items.Add or Items.Insert methods
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-10
Using the Properties Window - 1
• Define the Items collection at design time
– Select the control
– Scroll the Properties window to the Items
property
• Click the ellipsis button to open the String
Collection Editor
– Type the list items
– Click OK
– If needed, open the editor again to modify the list
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-11
Using the Properties Window - 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-12
Using the Items.Add Method
• Items that can be added to a list at run
time include:
– Variables, constants, contents of the text box
at the top of a combo box, or the text property
of another control
• Alter placement of a new item by setting
the control’s Sorted property to true
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-13
The Items.Add Method
• General Form
• Examples
• Use the Items.Add method to add a value entered in the text box portion of a combo box (not automatically added)
• Add contents of a text box to a list box
Object.Items.Add(ItemValue);
schoolsListBox.Items.Add("Harvard");
schoolsListBox.Items.Add("Stanford");
schoolsListBox.Items.Add(schoolsTextBox.Text);
majorsComboBox.Items.Add(majorsComboBox.Text);
majorsComboBox.Items.Add(majorString);
coffeeComboBox.Items.Add(coffeeComboBox.Text);
schoolsListBox.Items.Add(schoolTextBox.Text);
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-14
Using the Items.Insert Method
• Choose location for new item added to list
– Items.Insert method • Specify index position for new item
• An existing position or end of list
• Index position is zero based – First position, use index position = 0
• Inserting an item beyond end of list throws an exception
• Do not set list control’s Sorted property to true
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-15
The Items.Insert Method
• General Form
• Examples
Object.Items.Insert(IndexPosition, ItemValue);
schoolsListBox.Items.Insert(0, "Harvard");
majorsComboBox.Items.Insert(1, majorsComboBox.Text);
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-16
The SelectedIndex Property
• Index number of the currently selected item is stored in the SelectedIndex property
• If no list item is selected, the SelectedIndex property is negative 1 (–1)
• Set the SelectedIndex property in code to select an item in the list or deselect all items
// Select the fourth item in list.
coffeeTypesListBox.SelectedIndex = 3;
// Deselect all items in list.
coffeeTypesListBox.SelectedIndex = -1;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-17
The Items.Count Property
• Use to determine the number of items in the list
totalItemsInteger = itemsListBox.Items.Count;
MessageBox.Show(“The number of items in the list is ” +
itemsListBox.Items.Count.ToString());
• Items.Count is always one more than the highest possible SelectedIndex because indexes begin with zero – Example: For a list of five items
• Items.Count = 5
• Highest index = 4
• Possible values for SelectedIndex = 0, 1, 2, 3, 4
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-18
Referencing the
Items Collection - 1
• Use the index of the item to reference a
specific item in an Items collection
– Specify which element to select by including
an index
– Use square brackets to reference the index
position of a list
– Index of first list element is zero
– Highest index is Items.Count - 1
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-19
Referencing the
Items Collection - 2
• Combine the Items property and the SelectedIndex property to refer to a selected element of a list
selectedFlavorString = flavorListBox.Items[flavorListBox.SelectedIndex].ToString();
• Retrieve the selected list item by referring to the Text property of the control
selectedMajorLabel.Text = majorsComboBox.Text;
• Assigning a value to an item replaces previous contents of that position
schoolsListBox.Items[0] = “My School”;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-20
Removing an Item from a List
• Items.RemoveAt method – Removes an item by index
• First list element is 0, last element is Items.Count -1
– An invalid index will cause an IndexOutOfRange exception
namesListBox.Items.RemoveAt[0];
schoolsComboBox.Items.RemoveAt[indexInteger];
coffeeComboBox.Items.RemoveAt(coffeeComboBox.SelectedIndex);
• Items.Remove method – Looks for the specified string, removes item if string found
– No exception is generated if the item is not found
namesListBox.Items.Remove[“My School”];
schoolsComboBox.Items.Remove(schoolTextBox.Text);
coffeeComboBox.Items.Remove(coffeeComboBox.Text);
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-21
Clearing a List
• Items.Clear method
– Empty a combo box or list box
– Clear all items from a list
// Confirm clearing the majors list. DialogResult responseDialogResult; responseDialogResult = MessageBox.Show("Clear the majors list?", "Clear Majors List", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (responseDialogResult == DialogResult.Yes) { majorsComboBox.Items.Clear(); }
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-22
List Box and Combo Box Events
• SelectedIndexChanged event – Occurs when the user makes a selection from a list
• TextChanged event – Each keystroke generates a TextChanged event
– Available in combo boxes not list boxes
• Enter event – Occurs when a control receives the focus
– Use to make existing text appear selected
• Leave event – Fires when a control loses focus
– Often used for validating input data
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-23
The while and do/while Loops - 1
• Looping
– Process of repeating a series of instructions
• Loop
– Group of repeated instructions
• Iteration
– Single execution of the statement(s) in a loop
• while or do/while loop
– Terminates based on a condition specified
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-24
The while and do/while Loops - 2
• Execution of statements in the loop continue while a condition is true – Used when the exact number of iterations needed is not known
ahead of time
• while loop – Tests for completion at the top of a loop
– Also called a pretest or entry test
– Statements in loop never execute if terminating condition is true first time it is tested
– When statements inside loop do not execute, control passes to statement following end of loop
totalInteger = 0; while (totalInteger != 0) { // Statements in loop (will never be done). }
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-25
The while and do/while Loops - 3
• do/while loop
– Tests for completion at bottom of loop
– Also called a posttest or exit test
• Statements inside loop will always execute at least once
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-26
The bool Data Type Revisited
• bool variables can be very useful for setting and testing loop conditions – bool variables are always in one of two states—true or false
• Often referred to as switches or flags
– To use a bool variable for loop control
• Declare the variable and set its initial value
• When a particular situation occurs, set the variable to true
• Make the loop condition test for true (continue executing the loop as long as the condition is not true)
bool itemFoundBoolean = false; while (! itemFoundBoolean) // Loop when condition is false (not true). { // Statement(s) in loop. // Must include a statement that sets itemFoundBoolean to true. }
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-27
for Loops - 1
• Used to repeat statements in a loop a specific number of times
• Three parts of a for loop (statement), each separated by a semicolon – Initialization
• More than one initialization action can be used, separate each with commas
– Condition
– Action to occur after each iteration • More than one action to execute at end of each iteration of the loop
can be written
• Uses a numeric counter variable, the loop index, which is tested to determine the number of times the statements inside the loop will execute
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-28
for Loops - 2
• Counter-controlled loop normally has three elements – Initialize the counter
• The loop index, a properly initialized numeric variable
– Test the counter to determine when to terminate the loop
• Condition tests the value of the loop index variable
– Increment the counter • Add to or subtract from the loop index variable, the loop index
is incremented after each iteration
• All statements between a pair of braces following a for statement are the body of the loop – Statements are executed a specified number of times
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-29
The for Statement Examples
• Program checks condition after comparison is
done
• If condition is true, loop continues execution
• If condition is false, loop is exited
– Control passes to statement following closing brace
for (int indexInteger = 2; indexInteger <= 100; indexInteger += 2)
for (countInteger = startInteger; countInteger < endInteger; countInteger += incrementInteger)
for (int countInteger = 0; countInteger <= coffeeTypeComboBox.Items.Count – 1; countInteger++)
for (rateDecimal = 0.05M; rateDecimal < 0.25M; rateDecimal += 0.05M)
for (int countDownInteger = 10; countDownInteger > 0; countDownInteger– –)
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-30
Negative Increment or
Counting Backward
• Increment or decrement (reduce by one) the counter variable
• To decrement a counter variable write the condition to test for the lower bound
• Loop continues as long as index variable is greater than the test value
//Count down.
for (int countInteger = 10; countInteger > 0; countInteger--) { //Statements in the body of the loop. }
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-31
Conditions Satisfied before Entry
• Final value reached before entry into loop
– Statements in body of loop never executed
// An unexecutable loop.
int finalInteger = 5;
for (int indexInteger = 6; indexInteger < finalInteger; indexInteger++)
{
// The execution will never reach here.
}
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-32
Endless Loops
– Never change the value of the index variable
inside the loop
• Poor programming practice
• May lead to an endless loop
// Poor Programming.
For (int indexInteger = 1; indexInteger < 10; indexInteger++)
{
indexInteger = 1;
}
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-33
Exiting for Loops
– To exit an endless loop
• Click on an application's Close box
• Use the Stop Debugging button in the IDE
– Place a break statement to exit a for, while or
do/while loop
• Good programming practices dictate exiting loops
properly, not with a break
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-34
Skipping to the Next Iteration of a Loop
• Use a continue statement to skip the next iteration of the loop – Continue statement transfers control to the end of the
loop • Retests the loop exit condition
// Continue a for loop. for (int loopInteger = 0; loopInteger <= nameListBox.Items.Count – 1; loopInteger++) { if (nameListBox.Items[loopInteger].ToString() == string.Empty) { continue; } // Code to do something with the name found. Console.WriteLine("Name = " + nameListBox.Items[loopInteger].ToString()); }
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-35
Making Entries Appear Selected
• Make text in a text box or list appear selected
– If a text box fails validation, select the text
• Selecting the entry in a text box
– When a user tabs into a text box that already has an
entry, the user-friendly approach is to select the text
– Use the SelectAll method
– Place the SelectAll method in the text box’s Enter
event handler
• Occurs when the control receives the focus
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-36
Sending Information to the Printer
• Use the .NET PrintDocument and PrintPreviewDialog components from the Printing tab of the toolbox
• Printing is done through the Windows environment – Allows use of fonts installed on any given system
– Printing dialogs and page setup are the same as any other Microsoft product
• Several companies sell utilities that do a nice job of designing and printing reports
• C# Professional Edition and Team System Edition include Crystal Reports for creating reports from database files
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-37
The PrintDocument Component
• Set up output for
the printer using
methods and
events of the
PrintDocument
component
– Appears in
component tray
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-38
The PrintDocument Print Method
• Print method sends command to print
information according to the layout
specified in the PrintPage event handler
• Place Print method in the Click event
handler for a button or menu item
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-39
Setting Up the Print Output
• The code to set up the printed page belongs in the PrintDocument's PrintPage event handler
• The PrintPage event fires once for each page to be printed – This technique is referred to as a callback
– In a callback the object notifies the program it needs to do something by firing an event
• The PrintDocument Print method executes the PrintPage event handler – Holds code that describes exactly how pages should print
• The PrintDocument object also fires events for BeginPrint and EndPrint – Code can be written for these events
• System.Drawing.Printing.PrintPageEventArgs e argument – Properties and methods of PrintPageEventArgs
• Determines page margins and sends a string of text to the page
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-40
The Graphics Page
• Set up a graphics page in memory – Page is sent to the printer
• Page can contain strings of text and graphic elements
• Specify the exact X and Y coordinates of each element to be printed on the page – The X coordinate is the horizontal distance across the
page
– The Y coordinate is the vertical distance from the top of the page
– Measurements are in pixels
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-41
Using the DrawString Method
• Used to send a line of text to the graphics page
• Belongs to the Graphics object of the PrintPageEventArgs argument
• Is an overloaded method, there are several forms for calling the method
• Arguments of the DrawString method include – What to print
– What font and color to print in
– Where to print, using X and Y coordinates
• Set up the font and coordinates before executing the DrawString method
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-42
The DrawString Method
• General Form (One simple argument
list)
• Examples
GraphicsObject.DrawString(StringToPrint, Font, Brush, Xcoordinate, Ycoordinate);
e.Graphics.DrawString(printLineString, printFont, Brushes.Black, horizontalPrintLocationFloat, verticalPrintLocationFloat);
e.Graphics.DrawString("My text string", myFont, Brushes.Black, 100.0, 100.0);
e.Graphics.DrawString(nameTextBox.Text, new Font ("Arial", 10), Brushes.Red, leftMarginFloat, currentLineFloat);
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-43
Setting the X and Y Coordinates - 1
• For each print line, specify X and Y coordinates
• Create variables declared as float data type to hold the X and Y values
• The PrintPageEventArgs argument has several useful properties to determine the present settings – MarginBounds
– PageBounds
– PageSettings
• Example: Set the X coordinate to the current left margin and the Y coordinate to the top margin
horizontalPrintLocationFloat = e.MarginBounds.Left; verticalPrintLocationFloat = e.MarginBounds.Top;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-44
Setting the X and Y Coordinates - 2
• To print multiple lines, increment the Y coordinate (forces next line down the page) – Add the height of a line to the previous Y coordinate
to calculate the next line’s Y coordinate • Find height of a line in the current font using the font’s
GetHeight method
// Declarations at the top of the method. Font printFont = new Font("Arial", 12); float lineHeightFloat = printFont.GetHeight; float horizontalPrintLocationFloat = e.MarginBounds.Left; float verticalPrintLocationFloat = e.MarginBounds.Top;
// Print a line. e.Graphics.DrawString(printLineString, printFont, Brushes.Black, horizontalPrintLocationFloat, verticalPrintLocationFloat; // Increment the Y position for the next line. verticalPrintLocationFloat += lineHeightFloat;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-45
Printing Summary
• Easy steps for nearly all printing tasks – Place code in PrintPage event handler of the
PrintDocument component
1.At the top of the method, define the font(s), line height, and X and Y coordinates
2.Set up the line to print
3.Print the line
4. Increment the Y coordinate if another line will be printed
5.Place steps 2, 3, and 4 inside a loop if there are multiple lines to print
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-46
Printing the Contents of a List Box
• Combine the techniques for printing, looping, and the list box properties – The Items.Count property provides the number of iterations for
the loop
– The Items collection allows the actual values from the list to print // Print out all items in the coffeeComboBox list. for (int indexInteger = 0; indexInteger < coffeeComboBox.Items.Count; indexInteger++) { // Set up a line. printLineString = coffeeComboBox.Items[indexInteger]; // Send the line to the graphics page object. e.Graphics.DrawString(printLineString, printFont, Brushes.Black, horizontalPrintLocationFloat, verticalPrintLocationFloat); // Increment the Y position for the next line. verticalPrintLocationFloat += lineHeightFloat; }
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-47
Printing the Selected Item from a List
• Use the Text property to print the selected
item from a list box or combo box
// Set up the line. printLineString = “Coffee: ” + coffeeComboBox.Text + “ Syrup: ” + syrupListBox.Text; // Send the line to the graphics page object. e.Graphics.DrawString(printLineString, printFont, Brushes.Black, horizontalPrintLocationFloat, verticalPrintLocationFloat);
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-48
Aligning Decimal Columns - 1
• 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 – Has a Width property
• Use the MeasureString method of the Graphics class to determine the width of a formatted string in pixels
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-49
Aligning Decimal Columns - 2
// Print aligned columns. Font printFont = new Font("Arial", 12); float lineHeightFloat = printFont.GetHeight(); float yFloat = e.MarginBounds.Top; for (decimal indexDecimal = 0m; indexDecimal < 2000m; indexDecimal += 500m) { e.Graphics.DrawString("Text", printFont, Brushes.Black, e.MarginBounds.Left, yFloat); string formattedOutputString = indexDecimal.ToString("N"); //Measure the string using the font. SizeF fontSize = e.Graphics.MeasureString(formattedOutputString, printFont); // Determine start for number to end at column end. float column2Float = 500f – fontSize.Width; e.Graphics.DrawString(formattedOutputString, printFont, Brushes.Black, column2Float, yFloat); yFloat += lineHeightFloat; }
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-50
Displaying a Print Preview - 1
• View printer’s
output and choose
to print or cancel
– Helpful for testing
and debugging
• PrintPreviewDialog
component is key
• Add control to
component tray
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-51
Displaying a Print Preview - 2
• The PrintPreviewDialog component uses a PrintDocument component declared for printer output – Assign the PrintDocument to the Document property
of the PrintPreviewDialog
– Execute the ShowDialog method • The same PrintPage event handler executes as for the
PrintDocument
private void filePrintPreviewMenu_Click(object sender, System.EventArgs e) { // Begin the process for print preview. printPreviewDialog1.Document = printAllPrintDocument; printPreviewDialog1.ShowDialog(); }
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 7-52
Printing Multiple Pages
• The PrintDocument's PrintPage event fires
once for each page
• Set the HasMorePages property of the
PrintPageEventArgs argument to true to
print more than one page