C# Tutorial MSM_Murach chapter-03-slides

50
Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 1 C hapter3 How to code and testa W indow s Form s application

Transcript of C# Tutorial MSM_Murach chapter-03-slides

Page 1: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 1

Chapter 3

How to code and test a Windows Forms

application

Page 2: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 2

A form object and its ten control objects

Page 3: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 3

Class and object concepts An object is a self-contained unit that combines code and data.

Two examples of objects are forms and controls. A class is the code that defines the characteristics of an object.

You can think of a class as a template for an object. An object is an instance of a class, and the process of creating an

object from a class is called instantiation. More than one object instance can be created from a single class.

Then, each object has the same characteristics.

Page 4: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 4

Property, method, and event concepts Properties define the characteristics of an object and the data

associated with an object. Methods are the operations that an object can perform. Events are signals sent by an object to the application telling it

that something has happened that can be responded to. Properties, methods, and events can be referred to as members of

an object. If you instantiate two or more instances of the same class, all of

the objects have the same properties, methods, and events. However, the values assigned to the properties can vary from one instance to another.

Page 5: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 5

Objects and forms When you use the Form Designer, Visual Studio automatically

generates C# code that creates a new class based on the Form class. Then, when you run the project, a form object is instantiated from the new class.

When you add a control to a form, Visual Studio automatically generates C# code in the class for the form that instantiates a control object from the appropriate class and sets the control’s default properties.

When you move and size a control, Visual Studio automatically sets the properties that specify the location and size of the control.

Page 6: C# Tutorial MSM_Murach chapter-03-slides

Slide 6

Detour – How the IDE Creates Event Handlers Double click on the “Exit” button to get into the code editor. Do you see an event handler for clicking on the “Calculate”

button yet? Double click on the “Calculate” button Where the heck did this new code come from?

Page 7: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 7

A member list that’s displayed in the Code Editor window

Page 8: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 8

The syntax for referring to a member of a class or object

ClassName.MemberName objectName.MemberName

Statements that refer to properties txtTotal.Text = "10"; Assigns a string holding the number

10 to the Text property of the text box named txtTotal.

txtTotal.ReadOnly = true; Assigns the true value to the ReadOnly property of the text box named txtTotal so the user can’t change its contents.

Page 9: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 9

Statements that refer to methods txtMonthlyInvestment.Focus(); Uses the Focus method to move the

focus to the text box named txtMonthlyInvestment.

this.Close(); Uses the Close method to close the form that contains the statement. Here, this is a keyword that is used to refer to the current instance of the class.

Code that refers to an event btnExit.Click Refers to the Click event of a button

named btnExit.

Page 10: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 10

How to enter member names when working in the Code Editor window 1. To display a list of the available members for a class or an object,

type the class or object name followed by a period (called a dot operator, or just dot).

2. Type one or more letters of the member name, and the Code Editor will select the first entry in the list that matches those letters. Or you can scroll down the list to select the member you want.

3. Press the Tab or Enter key to insert the member into your code.

Note If a member list isn’t displayed, select the ToolsOptions

command to display the Options dialog box. Then, expand the Text Editor group, select the C# category, and check the Auto list members and Parameters information boxes.

Page 11: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 11

Event: The user clicks the Exit button

Wiring: The application determines what method to execute this.btnExit.Click += new System.EventHandler(this.btnExit_Click);

Response: The method for the Click event of the Exit button is executed private void btnExit_Click(object sender, System.EventArgs e) { this.Close(); }

Wiring is hidden for a reason but we can find it if we want!

Page 12: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 12

Common control events Event Occurs when… Click …the user clicks the control. DoubleClick …the user double-clicks the control. Enter …the focus is moved to the control. Leave …the focus is moved from the control.

Common form events Event Occurs when… Load …the form is loaded into memory. Closing …the form is closing. Closed …the form is closed.

Page 13: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 13

How an application responds to events Windows applications work by responding to events that occur on

objects. To indicate how an application should respond to an event, you

code an event handler, which is a special type of method that handles the event.

To connect the event handler to the event, Visual Studio automatically generates a statement that wires the event to the event handler. This is known as event wiring.

An event can be an action that’s initiated by the user like the Click event, or it can be an action initiated by program code like the Closed event.

Page 14: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 14

The method that handles the Click event of the Calculate button

Object Event

Page 15: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 15

How to handle the Click event of a button 1. In the Form Designer, double-click the control. This opens the Code

Editor, generates the declaration for the method that handles the event, and places the cursor within this declaration.

2. Type the C# code between the opening brace ({) and the closing brace (}) of the method declaration.

3. When you are finished writing code, you can return to the Form Designer by clicking the View Designer button in the Solution Explorer window.

How to handle the Load event for a form Follow the procedure above, but double-click the form itself.

Page 16: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 16

The completion list that’s displayed when you enter a letter at the beginning of a line of code

Page 17: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 17

The completion list that’s displayed as you enter code within a statement

Page 18: C# Tutorial MSM_Murach chapter-03-slides

Business Rules• Assume discount = 0%• If the Subtotal is $500 or more then the discount = 20%• If the Subtotal is $250 or more but less than $500 then

the discount = 15%• If the Subtotal is $100 or more but less than $250 then

the discount = 10%

• Go through a few examples by hand of calculating the discount percent, discount amount, and total

Slide 18

Page 19: C# Tutorial MSM_Murach chapter-03-slides

Slide 19

Subtotal ___________

Discount Percentage _______ >= $500 – 20% $250-$499.99 – 15% $100-$249.99 – 10%

Discount Amount Subtotal X Discount Percentage _______X_________________

Total Subtotal – Discount Amount _______ - ______________

Page 20: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 20

The event handlers for the Invoice Total form private void btnCalculate_Click(object sender, System.EventArgs e) { decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); decimal discountPercent = 0m; if (subtotal >= 500) { discountPercent = .2m; } else if (subtotal >= 250 && subtotal < 500) { discountPercent = .15m; } else if (subtotal >= 100 && subtotal < 250) { discountPercent = .1m; } decimal discountAmount = subtotal * discountPercent; decimal invoiceTotal = subtotal - discountAmount;

Page 21: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 21

The event handlers for the Invoice Total form (continued) txtDiscountPercent.Text = discountPercent.ToString("p1"); txtDiscountAmount.Text = discountAmount.ToString("c"); txtTotal.Text = invoiceTotal.ToString("c"); txtSubtotal.Focus(); } private void btnExit_Click(object sender, System.EventArgs e) { this.Close(); }

Page 22: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 22

Coding rules Use spaces to separate the words in each statement. Use exact capitalization for all keywords, class names, object

names, variable names, etc. End each statement with a semicolon. Each block of code must be enclosed in braces ({}). That

includes the block of code that defines the body of a method.

Page 23: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 23

The Code Editor and Error List windows with syntax errors displayed

Page 24: C# Tutorial MSM_Murach chapter-03-slides

Slide 24

How to detect and correct syntax errors Visual Studio checks the syntax of C# code as you enter it. If a

syntax error is detected, it’s highlighted with a wavy underline in the Code Editor window, and you can place the mouse pointer over it to display a description of the error.

If the Task List window is open, all of the syntax errors (or build errors) are listed in that window. Then, you can double-click on any error to take you to its location in the Code Editor window. When you correct the error, it’s removed from the task list.

By default, the Task List window is displayed when you build an application that contains a syntax error. To open this window and display the syntax errors before building the application, use the ViewOther WindowsTask List command.

Visual Studio doesn’t detect some syntax errors until the project is built. As a result, you may encounter more syntax errors when you build and run the project.

Page 25: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 25

A method written in a less readable style private void btnCalculate_Click(object sender, System.EventArgs e){ decimal subtotal=Convert.ToDecimal(txtSubtotal.Text); decimal discountPercent=0m; if (subtotal>=500) discountPercent=.2m; else if (subtotal>=250&&subtotal<500) discountPercent=.15m; else if (subtotal>=100&&subtotal<250) discountPercent=.1m; decimal discountAmount=subtotal*discountPercent; decimal invoiceTotal=subtotal-discountAmount; txtDiscountPercent.Text=discountPercent.ToString("p1"); txtDiscountAmount.Text=discountAmount.ToString("c"); txtTotal.Text=invoiceTotal.ToString("c");txtSubtotal.Focus();}

Page 26: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 26

A method written in a readable style private void btnCalculate_Click(object sender, System.EventArgs e) { decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); decimal discountPercent = 0m; if (subtotal >= 500) { discountPercent = .2m; } else if (subtotal >= 250 && subtotal < 500) { discountPercent = .15m; } else if (subtotal >= 100 && subtotal < 250) { discountPercent = .1m; } decimal discountAmount = subtotal * discountPercent; decimal invoiceTotal = subtotal - discountAmount;

Page 27: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 27

A method written in a readable style (continued) txtDiscountPercent.Text = discountPercent.ToString("p1"); txtDiscountAmount.Text = discountAmount.ToString("c"); txtTotal.Text = invoiceTotal.ToString("c"); txtSubtotal.Focus(); }

Page 28: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 28

Coding recommendations Use indentation and extra spaces to align statements and blocks

of code so they reflect the structure of the program. Use spaces to separate the words, operators, and values in each

statement. Use blank lines before and after groups of related statements.

Note As you enter code in the Code Editor window, Visual Studio

automatically adjusts its formatting by default.

Page 29: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 29

A method with comments private void btnCalculate_Click(object sender, System.EventArgs e) { /*************************************** * this method calculates the total * for an invoice depending on a * discount that's based on the subtotal ****************************************/ // get the subtotal amount from the Subtotal text box decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); // set the discountPercent variable based // on the value of the subtotal variable decimal discountPercent = 0m; // the m indicates a decimal value if (subtotal >= 500) { discountPercent = .2m; } else if (subtotal >= 250 && subtotal < 500) { discountPercent = .15m; }

Page 30: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 30

A method with comments (continued) else if (subtotal >= 100 && subtotal < 250) { discountPercent = .1m; } // calculate and assign the values for the // discountAmount and invoiceTotal variables decimal discountAmount = subtotal * discountPercent; decimal invoiceTotal = subtotal - discountAmount; // format the values and display them in their text boxes txtDiscountPercent.Text // percent format = discountPercent.ToString("p1"); // with 1 decimal place txtDiscountAmount.Text = discountAmount.ToString("c"); // currency format txtTotal.Text = invoiceTotal.ToString("c"); // move the focus to the Subtotal text box txtSubtotal.Focus(); }

Page 31: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 31

How to code comments Comments are used to help document what a program does and

what the code within it does. To code a single-line comment, type // before the comment. You

can use this technique to add a comment on its own line or to add a comment at the end of a line.

To code a delimited comment, type /* at the start of the comment and */ at the end. You can also code asterisks to identify the lines in the comment, but that isn’t necessary.

Page 32: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 32

The Code Editor window and the Text Editor toolbar

Page 33: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 33

How to use the buttons of the Text Editor toolbar To display or hide the Text Editor toolbar, right-click in the

toolbar area and choose Text Editor from the shortcut menu. To comment or uncomment several lines of code, select the lines

and click the Comment or Uncomment button. During testing, you can comment out a line of code. That way,

you can test a new statement without deleting the old statement. To increase or decrease the indentation of several lines of code,

select the lines and click the Increase Indent or Decrease Indent button. Or, press the Tab and Shift+Tab keys.

To move quickly between lines of code, you can use the last eight buttons on the Text Editor toolbar to set and move between bookmarks.

Page 34: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 34

How to collapse or expand regions of code If a region of code appears in the Code Editor with a minus sign

(-) next to it, you can click the minus sign to collapse the region so just the first line is displayed.

If a region of code appears in the Code Editor with a plus sign (+) next to it, you can click the plus sign to expand the region so all of it is displayed.

Page 35: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 35

The Code Editor with enlarged text and a highlighted variable

Page 36: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 36

The default list of Visual C# code snippets

Page 37: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 37

A code snippet after it has been inserted

Page 38: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 38

The bar that appears under a renamed variable

The menu that’s available from the bar

Page 39: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 39

The Preview Changes dialog box

Page 40: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 40

The Help Viewer

Page 41: C# Tutorial MSM_Murach chapter-03-slides

Slide 41

How to run a project To run a project, click the Start button in the Standard toolbar,

select the DebugStart menu command, or press the F5 key. This causes Visual Studio to build the project and create an assembly.

If no build errors are detected, the assembly is run so the project’s form is displayed over the IDE.

If build errors are detected, they’re listed in the Task List window and a dialog box asks whether you want to run the project even though there were build errors. Click No to return to the Code Editor.

To locate a statement in error, you can double-click on the error description in the Task List window. After you’ve corrected all the errors, run the project again to rebuild it and clear the errors.

To build a project without running it, select the BuildBuild project name command.

Page 42: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 42

The form displayed when you run the Invoice Total project

Page 43: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 43

The Exception Assistant that’s displayed when a runtime error occurs

Page 44: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 44

How to test a project 1. Test the user interface. Visually check all the controls to make

sure they are displayed properly with the correct text. Use the Tab key to make sure the tab order is set correctly, verify that the access keys work right, and make sure that the Enter and Esc keys work properly.

2. Test valid input data. For example, enter data that you would expect a user to enter.

3. Test invalid data or unexpected user actions. For example, leave required fields blank, enter text data into numeric input fields, and use negative numbers where they are not appropriate. Try everything you can think of to make the application fail.

Page 45: C# Tutorial MSM_Murach chapter-03-slides

Murach’s C# 2010, C3 © 2010, Mike Murach & Associates, Inc. Slide 45

How a project looks in break mode

Page 46: C# Tutorial MSM_Murach chapter-03-slides

Slide 46

How to debug runtime errors When an application ends with a runtime error, you need to fix

the error. This is commonly referred to as debugging, and the error is commonly referred to as a bug.

If you click the Break button in the dialog box for a runtime error, Visual Studio displays the Code Editor window and highlights the statement that caused the exception.

When a program enters break mode, the debugging windows and the Debug and Debug Location toolbars are displayed.

In break mode, you can display the value of a variable or property in a data tip by positioning the mouse pointer over it.

To exit break mode and end the application, click the Stop Debugging button in the Debug toolbar.

To enter break mode any time that an application is running, click the Break All button in the Debug toolbar. This is useful if you need to stop a program that’s caught in a loop.

Page 47: C# Tutorial MSM_Murach chapter-03-slides

Slide 47

In-Class Activity

• Can you– Code the “Exit” button– Code the “Calculate..” to

• Access txtNumericGrade.Text• Convert it to a decimal and store it in a variable• Add 10 to this variable• Convert this into a string and store it in the Text property of

lblLetterGrade– Yes, I know this is a silly thing but I just want to get

you accessing & working with the Text property of controls

Text box

Label

Page 48: C# Tutorial MSM_Murach chapter-03-slides

Slide 48

In-Class Activity

• Can you– Code the “Exit” button– Code the “Calculate..” button to

• Access txtOrderTotal.Text• Convert it to a decimal and store it in a variable• Add 10 to this variable• Convert this into a string and store it in the Text property of

txtGrandTotal– Yes, I know this is a silly thing but I just want to get

you accessing & working with the Text property of controls

Text boxes

Read Only Text Boxes

Page 49: C# Tutorial MSM_Murach chapter-03-slides

Slide 49

In-Class Activity

• Can you– Code the “Exit” button– Code the “Project..” button to

• Access txtNumberOfStudentsToday.Text• Convert it to a decimal and store it in a variable• Double this number• Convert this into a string and store it in the Text property of

txtNumberOfProjectedStudents– Yes, I know this is a silly thing but I just want to get

you accessing & working with the Text property of controls

Text boxes

Read Only Text Box

Page 50: C# Tutorial MSM_Murach chapter-03-slides

Slide 50

In-Class Activity

• Can you– Code the “Exit” button– Code the “Convert..” button to

• Access txtAlphanumericNumber.Text• Store it in text property of txtNumericOnly

– Yes, I know this is a silly thing but I just want to get you accessing & working with the Text property of controls