30
PAKISTAN NAVY ENGINEERING COLLEGE, NATIONAL UNIVERSITY OF SCIENCES AND TECHNOLOGY, KARACHI. CS‐312 ‐ COMPUTER PROGRAMMING STUDENT’S LAB MANUAL Revised version Fall 2012 Edited and Compiled by Ms. Aisha Malik Lab Engineer EPE Department

CP Lab Manual

Embed Size (px)

Citation preview

Page 1: CP Lab Manual

PAKISTAN NAVY ENGINEERING COLLEGE, NATIONAL UNIVERSITY OF SCIENCES AND TECHNOLOGY, KARACHI. 

CS‐312 ‐ COMPUTER PROGRAMMING    

STUDENT’S LAB MANUAL  

Revised version Fall 2012 

   

Edited and Compiled by Ms. Aisha Malik Lab Engineer 

EPE Department  

 

 

Page 2: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 1

Introduction to the Visual C# IDE – Overview and Layout

Objective: To learn the basics of Visual C# Integrated Development Environment Description:

When Microsoft Visual Studio 2005 is executed for the first time, the Start Page is displayed with several windows including helpful links. Note: There are slight differences in the way Visual Studio appears based on the version being used. Under the Start Page tab comes several sections: 1. The Getting Started section contains links to the online help and guide for the beginners. If the user is not connected to the internet, the selected topic is searched in the local help in Visual Studio. 2. Recent Projects section contains links to recently opened projects. The most recently opened projects appear on this list. Alternately, you can go to the select Recent Projects from the File menu. 3. The Visual Development Center section displays new features and updates for Visual Studio, including downloads for code samples and new programming tools. 4. The Visual Studio Headlines section provides a way to browse news, articles and how-to guides. Besides the Start Page, the IDE contains windows which are necessary for modifying and/or viewing the progress of the code. User can select which windows to display in the IDE and can select its layout.

The left panel is the Solution Explorer window which shows the contents of the project. The bottom window is to view the progress of the program in a tabbed form. These tabs for example, can include the Output Window where user can see the compilation, the building and the debugging of the program. Likewise, user can view the list of errors in the code from the Error List window.

Page 3: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

__________________________________________

Page 4: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 2-A

A simple visual Program – How to display a text and an image Objective: To display a text message and an image on the screen using Windows Application Description: With C#, a program can be created with multiple types of output (windows, dialogs and so forth). These programs are called Windows applications and provide graphical user interfaces. Windows applications are programs that execute inside the Windows OS, like Microsoft Word, Internet Explorer and Visual Studio. Typically, they contain controls —graphical elements, such as buttons and labels — with which the user interacts.

Steps to Follow:

1. Create a new project with the name of “My first GUI” 2. Set the Form’s Title Bar 3. Resize the form 4. Change the form’s Background Color 5. Add a label Control to the form and set the label’s Text 6. Add a picture box in the form and insert an image 7. Save and run the project

Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

Page 5: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 2-B

Simple Program – Printing a Line of Text

Objective: To print a line of text using a console application Description: There are several types of projects that we can create in C#; the console application is one of the basic types. Console applications are applications that contain only text output. Text output in a console application is displayed in a console window. Steps to Follow:

1. First, create a new project of the type console application 2. Write the following line under within the Main Method body:

Console.WriteLine (“Welcome to C# Programming”);

3. Build the program to check for any syntax errors 4. Save and execute the program

Output: The output should be as follows:

Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

Page 6: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 3

Methods

Objective:

To practice with built-in Math Methods To write user-defined Methods

Description: Methods allow programmers to modularize programs. There are several motivations for modularizing a program with methods. The divide- and- conquer approach makes program development more manageable. Another motivation is software reusability—using existing methods (and classes) as building blocks to create new programs. With proper method naming and definition, we can create programs from standardized methods, rather than building customized code. Math class methods allow the programmer to perform certain common mathematical calculations. Methods are called by writing the name of the method, followed by a left parenthesis, the argument (or a comma-separated list of arguments) of the method and a right parenthesis. The parentheses may be empty, if we are calling a method that needs no information to perform its task. We now consider how to write customized methods. The format of a method definition is: return-value-type method-name( parameter-list )

{ declarations and statements

} The first line is sometimes known as the method header. The method-name is any valid identifier. The return-value-type is the data type of the result that the method returns to its caller. The return-value-type void indicates that a method does not return a value. Methods can return at most one value. The parameter-list is a comma-separated list in which the method declares each parameter’s type and name. The method call must specify one argument for each parameter in the method definition and the arguments must appear in the same order as the parameters in the method definition. The arguments also must be compatible with the parameter’s type. For example, a parameter of type double could receive values of 7.35, 22 or –.03546, but not "hello" because a double variable cannot contain a string. If a method does not receive any values, the parameter list is empty (i.e., the method name is followed by an empty set of parentheses). Each parameter in a method’s parameter list must have a data type; otherwise, a syntax error occurs.

Page 7: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

There are three ways to return control to the point at which a method was invoked. If the method does not return a result (i.e., the method has a void return type), control returns when the program reaches the method-ending right brace or when the statement return; executes. If the method does return a result, the statement return expression; returns the value of expression to the caller. When a return statement executes, control returns immediately to the point at which the method was invoked.

Page 8: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Class Assignment: Write your own method using windows application that calculates the square root, power, maximum and minimum of the inputs given by the user in the text boxes. Submit the code along with th output snapshots. Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

__________________________________________________________________

Page 9: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 5-A

Decision/Selection Statements – If and If/else

Objective: To practice with single selection, double selection and multiple selection structures using Console Application Description: C# provides three types of selection structures. The if selection structure performs (selects) an action if a condition is true or skips the action if the condition is false. The if/else selection structure performs an action if a condition is true and performs a different action if the condition is false. The switch selection structure performs one of many actions, depending on the value of an expression. The if structure is called a single-selection structure because it selects or ignores a single action (or a single group of actions). The if/else structure is called a double-selection structure because it selects between two different actions (or groups of actions). The switch structure is called a multiple-selection structure because it selects among many different actions (or groups of actions). In this lab, we will cover the if and if/else selection structures. The lecture will cover the explanation of the syntax. Class Assignment: Write a console application for each of the following pseudo code statements:

• If Statement: If student’s grade is greater than or equal to 60 Print “Passed”

• If - else Statement: If student’s grade is greater than or equal to 60 Print “Passed” Else Print “Failed”

Page 10: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

• If – else – if: If student’s grade is greater than or equal to 90 Print “A” Else If student’s grade is greater than or equal to 80 Print “B” Else If student’s grade is greater than or equal to 70 Print “C” Else If student’s grade is greater than or equal to 60 Print “D” Else Print “F” Take a snapshot of the output window. Submit the code and the output window as a Word document along with this handout. Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, December, 2005

______________________________________

Page 11: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 5B

Decision/Selection Statements - Switch

Objective: To practice with switch multiple selection statement using Console Application Description: Occasionally, an algorithm contains a series of decisions in which the algorithm tests a variable or expression separately for each constant integral expression or constant string expression the variable or expression may assume. A constant integral expression is any expression involving character and integer constants that evaluates to an integer value. A constant string expression is any expression composed of string literals that always results in the same string. The algorithm then takes different actions based on those values. C# provides the switch multiple-selection structure to handle such decision making. This lab session will cover the explanation of the syntax. Class Assignment: Write a program that takes an alphabet from the user as input and prints whether the input is a consonant or a vowel using switch statement. Take a snapshot of the output window. Submit the code and the output window as a Word document along with this handout. Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

__________________________________________

Page 12: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 6

Repetition statements – While Loop

Objective: To practice with while, for and do-while loop statements Description: A repetition structure allows the programmer to specify that an action is to be repeated while a condition remains true. The pseudo code statement:

While there are more items on my shopping list Purchase next item and cross it off my list

describes the repetition that occurs during a shopping trip. The condition, “there are more items on my shopping list” may be true or false. If it is true, then the action, “Purchase next item and cross it off my list” is performed. This action executes repeatedly while the condition remains true. The statement(s) contained in the while repetition structure constitute the body of the while. The while structure body may be a single statement or a block. Eventually, the condition becomes false (when the last item on the shopping list has been purchased and crossed off the list). At this point, the repetition terminates, and the first statement after the repetition structure executes. The for repetition structure handles the details of counter-controlled repetition.The for structure specifies each of the items needed for counter-controlled repetition with a control variable. The for structure specifies each of the items needed for counter-controlled repetition with a control variable. If there is more than one statement in the body of the for, braces ({ and }) are required to define the loop’s body.

Page 13: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

The do/while repetition structure is similar to the while structure. In the while structure, the test of the loop-continuation condition occurs at the beginning of the loop, before the body of the loop executes. The do/while structure tests the loop-continuation condition after the loop body executes; therefore, the loop body always executes at least once. When a do/ while structure terminates, execution continues with the statement after the while clause. Essentials of Counter-Controlled Repetition 1. The name of a control variable (or loop counter), used to determine whether the loop

continues. 2. The initial value of the control variable. 3. The increment (or decrement) by which the control variable is modified each time through the

loop (also known as each iteration of the loop). 4. The condition that tests for the final value of the control variable (i.e., whether looping should

continue). Class Assignment: Solve the following problem statement with the help of the syntax of while statement explained in the session: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. Submit the code and the output window as a Word document along with this handout. Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

__________________________________________

Page 14: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 7- A

Forms, Controls and Components

Objective: To understand the properties of forms, controls and components

Windows Forms Windows Forms create GUIs for programs. A form is a graphical element that appears on the desktop. A form can be a dialog or a window.

Fig. 1 Some basic GUI components A component is a class that implements the IComponent interface, which defines the behaviors that components must implement. A control, such as a button or label, is a component with a graphical part. Controls are visible, whereas components, which lack graphical parts, are not. Figure 2 displays the Windows Forms controls and components contained in the Visual Studio .NET Toolbox—the first two screens show the controls and the last screen shows the components. When the user selects a component or control, the user then can add that component or control to the form.

Page 15: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Fig. 2 The form acts as a container for components and controls. Controls must be added to the form using code. When we drag a control from the Toolbox onto the form, Visual Studio .NET generates this code for us, which instantiates the control and sets the control’s basic properties. We could write the code ourselves, but it is much easier to create and modify controls using the Toolbox and Properties window, letting Visual Studio .NET handle the details. When the user interacts with a control by using the mouse or keyboard, events are generated, and event handlers process those events. Events typically cause something to happen in response. For example, clicking the OK button in a MessageBox generates an event. An event handler in class MessageBox closes the MessageBox in response to this event. The general design process for creating Windows applications requires creating a Windows Form, setting its properties, adding controls, setting their properties and implementing the event handlers. Figure 3 lists common Form properties and events.

Page 16: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Fig. 3 Visual Studio .NET generates most GUI-related code when we create controls and event handlers. Programmers can use Visual Studio .NET to perform most of these tasks graphically, by dragging and dropping components onto the form and setting properties in the Properties window. In visual programming, the IDE generally maintains GUI-related code, and the programmer writes the event handlers. Control Properties and Layout Controls derive from class Control (namespace System.Windows.Forms). Figure 4 contains a list of common properties and events for class Control. The Text property specifies the text that appears on a control, which may vary depending on the context. For example, the text of a Windows Form is its title bar, and the text of a button appears on its face. The Focus method transfers the focus to a control. When the focus is on a control, it becomes the active control. When the Tab key is pressed, the TabIndex property determines the order in which controls are given focus. The TabIndex property is automatically set by Visual Studio .NET, but can be changed by the programmer. This is helpful for the user who enters information in many different locations—the user can enter information and quickly select the next control by pressing the Tab key. The Enabled property indicates whether the control can be used. Programs can set property Enabled to false when an option is unavailable to the user. In most cases, the control’s text will appear gray (rather than black), when a control is disabled. Without having to disable a control, the control can be hidden from the user by setting the Visible property to false or by calling method Hide. When a control’s Visible property is set to false, the control still exists, but it is not shown on the form.

Page 17: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Fig. 4

Page 18: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session – 7 B

Control Properties – Anchor and Dock

Objective: To practice and manipulate the Anchor and Dock properties of a control Description: Visual Studio .NET allows the programmer to anchor and dock controls, which help to specify the layout of controls inside a container (such as a form). Anchoring allows controls to stay a fixed distance from the sides of the container, even when the control is resized. Docking allows controls to extend themselves along the sides of their containers. A user may want a control to appear in a certain position (top, bottom, left or right) in a form even when that form is resized. The user can specify this by anchoring the control to a side (top, bottom, left or right). The control then maintains a fixed distance from the side to its parent container. In most cases, the parent container is a form; however, other controls can act as a parent container. When parent containers are resized, all controls move. Unanchored controls move relative to their original position on the form, while anchored controls move so that they will be the same distance from each side that they are anchored to. For example, in Fig. 11.1, the topmost button is anchored to the top and left sides of the parent form. When the form is resized, the anchored button moves so that it remains a constant distance from the top and left sides of the form (its parent). The unanchored button changes position as the form is resized. Steps to Follow:

1. Create a simple Windows application that contains two controls. 2. Anchor one control to the right side by setting the Anchor property as shown in Fig. 9.2.

Leave the other control unanchored. Now, resize the form by dragging the right side farther to the right.

Notice that both controls move. The anchored control moves so that it is always the same distance to the right wall. The unanchored control moves so that it is in the same place on the form, relative to each side. This control will continue to be somewhat closer to whatever sides it was originally close to, but will still reposition itself when the user resizes the application window.

Page 19: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Fig. 9.1

Fig. 9.2 Sometimes a programmer wants a control to span the entire side of the form, even when the form is resized. This is useful when we want one control to remain prevalent on the form, such as the status bar that might appear at the bottom of a program. Docking allows a control to spread itself along an entire side (left, right, top or bottom) of its parent container. When the parent is resized, the docked control resizes as well. In Fig. 9.3, a button is docked to the top of the form. (It lies across the top portion.) When the form is resized, the button is resized as well—the button always fills the entire top portion of the form. The Fill dock option effectively docks the control to all sides of its parent, which causes it to fill its entire parent. Windows Forms contain property DockPadding, which sets the distance from docked controls to the edge of the form. The default value is zero, causing the controls to attach to the edge of the form.

Page 20: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Fig. 9.3 Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

__________________________________________

Page 21: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session – 8

Labels, Textboxes and Buttons

Objective: To learn the use of Textbox, Label and Buttons by writing a program that displays the password entered in the textbox after the button is pressed. Description: Labels provide text instructions or information about the program. Labels are defined with class Label, which derives from class Control. A Label displays read-only text, or text that the user cannot modify. Once labels are created, programs rarely change their contents. A textbox (class TextBox) is an area in which text can be either input by the user from the keyboard or displayed. A password textbox is a TextBox that hides what the user entered. As the user types in characters, the password textbox displays only a certain character (usually *). Altering the PasswordChar property of a textbox makes it a password textbox and sets the appropriate character to be displayed. Deleting the value of PasswordChar in the Properties window sets the textbox back to a regular textbox. A button is a control that the user clicks to trigger a specific action. A program can use several other types of buttons, such as checkboxes and radio buttons. Steps to Follow:

1. First, create the GUI by dragging the components (a Button, a Label and a TextBox) onto the form.

2. Change their names in the Properties window (by setting the (Name) property) from the default values — textBox1, label1, button1 — to displayPasswordLabel, inputPasswordTextBox and displayPasswordButton.

3. Then set displayPasswordLabel’s Text property to “Show Me” and clear the Text of

displayPasswordLabel and inputPasswordTextBox so that they are initially blank when the program runs.

4. Set the BorderStyle property of displayPasswordLabel to Fixed3D.

5. The password character is set by assigning the asterisk character (*) to the

PasswordChar property. This property can take only one character.

6. Now, write a suitable line in the code that displays the entered text in the textbox in the Label after the button is pressed.

Page 22: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

__________________________________________

Page 23: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session – 9

Check Boxes Objective: To practice exercise on Check Boxes Description: Visual C# has two types of state buttons—CheckBox and RadioButton—that can be in the on/off or true/false state. Classes CheckBox and RadioButton are derived from class ButtonBase. We focus on the CheckBoxes in this Lab session. A checkbox is a small white square that can be blank or contain a checkmark. When a checkbox is selected, a black checkmark appears in the box. There are no restrictions on how checkboxes are used: Any number may be selected at a time. The text that appears alongside a checkbox is referred to as the checkbox label. Task: To write a program that allows the user to select a CheckBox to change the font style of a Label. One CheckBox applies a bold style, the other an italic style. If both checkboxes are selected, the style of the font is bold and italic. When the program initially executes, neither CheckBox is checked. Steps to Follow:

1. First, create the GUI by dragging the components (Two checkboxes and a Label) onto the form.

2. Name the first CheckBox as boldCeckBox with the Text property set to Bold. 3. Name the other CheckBox as italicCheckBox and label italic. 4. Name the Label as outputLabel and label it as Watch the font style change. 5. Define their event handlers. Double click bold-CheckBox to create and register an

empty CheckedChanged event handler. 6. Add the following lines to this event handler:

private void boldCheckBox_CheckedChanged (object sender, System. EventArgs e ) {

outputLabel.Font = new Font( outputLabel.Font.Name, outputLabel.Font.Size, outputLabel.Font.Style ^ FontStyle.Bold ) ;

}

Page 24: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

7. Repeat steps 5 and 6 for the italic-CheckBox.

Explanation: In this program, we need to set the font style so that the text will appear bold if it was not bold originally, and vice versa. We use the bitwise XOR operator (^) to do this. Applying this operator to two bits does the following: If exactly 1 one of the corresponding bits is 1, set the result to 1. By using the ^ operator, we are setting the bit values for bold in the same way. The operand on the right (FontStyle.Bold) always has bit values set to bold. The operand on the left, then outputLabel.Font.Style) must not be bold for the resulting style to be bold. If outputLable.Font.Style is bold, then the resulting style will not be bold. This operator also allows us to combine the styles.

Output:

______________________________________________________________

Page 25: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 10

Group Boxes and Panels

Objective: To practice the basics of Group Boxes and Panels Description: GroupBoxes and Panels arrange components on a GUI. For example, buttons related to a particular task can be placed inside a GroupBox or Panel inside the Visual Studio .NET form designer. All these buttons move together when the GroupBox or Panel is moved. The main difference between the two classes is that GroupBoxes can display a caption, and Panels can have scrollbars. The scrollbars allow the user to view additional controls inside the Panel by scrolling the visible area. GroupBoxes have thin borders by default, but Panels can be set to have borders by changing their BorderStyle property. Task: Write a program to bring the following output:

Page 26: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session - 11

Radio Buttons and Message Boxes Objective: To understand the use of Radio Buttons and types of Message Boxes Task: To use radio buttons to select the options for a MessageBox. Users select the attributes they want then press the display button, which causes the MessageBox to appear. A Label in the lower-left corner shows the result of the MessageBox (Yes, No, Cancel, etc.) Display your own output windows. Description:

Page 27: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Output Windows:

Page 28: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

____________________________________________________________________

Page 29: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Lab Session 12

Picture Boxes Objective: To understand the use of Picture boxes using Windows application Description: A picture box (class PictureBox) displays an image. The image can be in a bitmap (.bmp), .gif, .jpg, icon or metafile format. GIF (Graphics Interchange Format) and JPEG (Joint Photographic Expert Group) files are widely used file formats. The Image property sets the Image object to use, and the SizeMode property sets how the image is displayed (Normal, StretchImage, AutoSize or CenterImage). Task: Use PictureBox imagePictureBox to display one of three .jpg images—image0, image1 or image2. Store these three .jpg images in a folder named Images located in the bin/debug directory of your project where the executable file is located. Whenever the imagePictureBox is clicked, the image changes. The Label (named promptLabel) on the top of the form includes the instructions Click On Picture Box to View Images. Explanation: To respond to the user’s clicks, we must handle the Click event. Inside the event handler, we use an integer (imageNum) to store the image we want to display. We then set the Image property of imagePictureBox to an Image. Class Image is discussed in Chapter 16, Graphics and Multimedia, but here we overview method From- File, which takes a string (the path to the image file) and creates an Image object. To find the images, we use class Directory (namespace System.IO) method GetCurrentDirectory. This returns the current directory of the executable file (usually bin\Debug) as a string. To access the images subdirectory, we take the current directory and append “\\images” followed by “\\” and the file name. We use a double slash because an escape sequence is needed to print a single slash. imageNum is used to append the proper number in order to load either image0, image1 or image2. Integer imageNum stays between 0 and 2, due to the modulus calculation. Finally, ".jpg" is appended to the filename. Thus, if we want to load image0, the string becomes “CurrentDir\images\image0.jpg”, where CurrentDir is the directory of the executable.

Page 30: CP Lab Manual

CS‐312 ‐ COMPUTER PROGRAMMING    

CS – 312 COMPUTER PROGRAMMING   

Output: Output should be as follows:

Reference: Visual C-Sharp 2005 How to Program (2e), by Dr. Harvey M. Deitel, Paul J. Deitel, Dec 2005

________________________________________________________________