Notes for Visual Fifth Edition Chapter 3 – Processing Data

3.1 Reading Input with TextBox Control

  • TextBox control: a rectangular area that can accept keyboard input from the user.
  • Located in the Common Controls group of the Toolbox.
  • Double click to add it to the form.
  • Default name is textBoxn, where n is 1, 2, 3, …

3.2 A First Look at Variables

  • A variable is a storage location in memory.
  • A variable name represents the memory location.
  • In the language (shown) you must declare a variable in a program before using it to store data.
  • Syntax to declare variables: DataType VariableName;

3.3 Numeric Data Types and Variables

  • If you need to store a number for calculations, use a numeric data type.
  • Common numeric data types:
    • int: whole numbers in the range 2,147,483,648 to 2,147,483,647-2{,}147{,}483{,}648 \text{ to } 2{,}147{,}483{,}647
    • double: real numbers, including fractional parts.
  • A numeric literal is a number written in code and is not enclosed in quotes.

3.4 The decimal Data Type

  • The decimal keyword indicates a 128-bit numeric type.
  • It has more precision and a smaller range compared to double, making it suitable for financial calculations.
  • To denote a decimal value, suffix with MM (or mm): e.g. 12.34M12.34M.

3.5 Explicit Conversion with Cast Operators

  • Explicit conversion (type casting) allows you to convert between types.
  • Cast operator uses parentheses with the target type, e.g. (type)value(\text{type}) value.

3.5 Performing Calculations

  • Basic arithmetic operators:
    • ++: Addition
    • -: Subtraction
    • *: Multiplication
    • //: Division
    • %\%: Modulus

3.6 Rules for Performing Calculations

  • A math expression performs a calculation and yields a value.
  • Follow the order of operations; use parentheses to group as needed.
  • Mixed-type results:
    • If an operation involves intint and doubledouble, the int is treated as a double and the result is doubledouble.
    • If an operation involves intint and decimaldecimal, the int is treated as decimaldecimal and the result is decimaldecimal.
    • An operation involving a doubledouble and a decimaldecimal is not allowed.

3.7 Integer Division

  • If you divide an integer by an integer, the result is always an integer (truncated toward zero).
  • Example: the result is 22 for some integer division.
  • To avoid integer division, promote at least one operand to a floating point type (e.g., cast to doubledouble or use a double/doubledouble/double expression).

3.5 Inputting and Outputting Numeric Values

  • Keyboard input is read as strings (even if it represents a number). A TextBox reads input like 25.6525.65 but treats it as a string.
  • Use Parse methods to convert string to numeric types:
    • int.Parseint.Parse, double.Parsedouble.Parse, decimal.Parsedecimal.Parse
  • Examples are shown in practice code.

3.5 Displaying Numeric Values

  • The Text property of a control accepts only string literals.
  • To display a number, convert the numeric value to a string using ToString()ToString() or perform implicit string conversion with the + operator.

3.6 Formatting Numbers with the ToString Method

  • The ToString method can format a number in various ways using format strings.
  • Examples of common format strings:
    • Number format (default) via ToString()ToString()
    • ToString(n¨3)¨ToString(\"n3\")12.30012.300
    • Fixed-point: ToString(f¨2)¨ToString(\"f2\")123456.00123456.00
    • Exponential/scientific: ToString(e¨3)¨ToString(\"e3\")1.235e+0051.235e+005
    • Currency: ToString(C¨)¨ToString(\"C\") → e.g. ($1,234,567.80)
    • Percentage: ToString(P¨)¨ToString(\"P\") → e.g. 23.40%23.40\%
  • Other notes:
    • The output examples illustrate formatting rather than changing the numeric value.

3.7 Simple Exception Handling

  • An exception is an unexpected error that occurs while a program runs.
  • If not handled, the program may halt abruptly.
  • Exception handling allows reacting to errors with code blocks known as exception handlers.
  • The structure used is a trycatchtry-catch statement:
    • The trytry block contains statements that could throw exceptions.
    • The catchcatch block contains statements to execute in response to the exception.

3.8 Using Named Constants

  • A named constant represents a value that cannot change during program execution.
  • Declared with the constconst keyword.
  • Conventional naming often uses uppercase letters for constants, but this is not mandatory.

3.9 Declaring Variables as Fields

  • A field is a variable declared at the class level, inside the class but outside any method.
  • A field’s scope is the entire class.
  • In the Field Demo application, the namename variable is a field and is created in memory when the Form1 form is created.

3.10 Using the Math Class

  • The .NET Framework’s Math class provides methods for complex math:
    • Math.Sqrt(x)Math.Sqrt(x) returns the square root of xx (a doubledouble).
    • Math.Pow(x,y)Math.Pow(x, y) returns xyx^y; both xx and yy are doubledouble.
  • Predefined constants:
    • Math.PIMath.PI represents the ratio of a circle's circumference to its diameter.
    • Math.EMath.E represents the base of natural logarithms.

3.11 More GUI Details – Tab Order

  • Focus: the control currently receiving keyboard input.
  • When the tab key is pressed, the program moves through controls in tab order.
  • The order is determined by the TabIndexTabIndex property; indices start at 0 (the first control has index 0).

3.11 Tab Order (1 of 2)

  • To set tab order, select Tab Order from the View menu, then click controls in the desired order.
  • Label controls cannot receive keyboard input and their TabIndex values are irrelevant.

3.11 Tab Order (2 of 2)

  • You can change focus programmatically with the Focus() method, e.g. to set focus to a specific TextBox when a button is clicked.
  • Example concept: clicking Clear sets focus to nameTextBoxnameTextBox.

3.12 Assign Keyboard Access Key to Buttons

  • An access key (mnemonic) allows quick access via Alt-key combinations.
  • Set by placing an ampersand (&) before a letter in a Button's Text property.
  • Example: setting Text to &Save makes Alt+S activate the button.
  • Access keys are case-insensitive.

3.12 Setting Colors

  • BackColor property controls the background color of a Form or control.
  • ForeColor property controls text color for controls that display text.
  • Color selection provides a drop-down with tabs: Custom, Web, System.
  • These color values are provided by the .NET Framework.

3.12 Background Images for Forms

  • Form has a BackgroundImage property similar to a PictureBox's Image property; images can be imported via the Resources window.
  • BackgroundImageLayout property controls how the image is laid out; options are analogous to the SizeMode choices for PictureBox.

3.12 GroupBoxes vs Panels

  • GroupBox: a container with a border and an optional title (Text property).
  • Panel: a container without a title; no Text property.
  • Differences:
    • Panel’s border is controlled by its BorderStyle property; GroupBox does not have a BorderStyle in the same way.
    • GroupBox supports a Text/title; Panel does not.

3.12 Using the Debugger to Locate Logic Errors

  • A logic error is a bug that does not stop the program from running but produces incorrect results (e.g., math errors, assigning wrong values).
  • Debugging tools in Visual Studio help locate such errors.

Breakpoints (1 of 2)

  • A breakpoint is a line of code where execution will pause.
  • When execution reaches a breakpoint, the program enters break mode.
  • In break mode, you can inspect variable contents and control properties.

Breakpoints (2 of 2)

  • How to break into code:
    • Click in the left margin to set a breakpoint, or
    • Use the Breakpoints window to manage them.
  • Example snippet related to a breakpoint:
    • Average Race Times example (simplified):
    • Code fragment:
    • csharp double runner1; double runner2; double runner3; double average; // Get the times entered by the user. runner1 = double.Parse(runner1TextBox.Text); runner2 = double.Parse(runner2TextBox.Text); runner3 = double.Parse(runner3TextBox.Text); // Calculate the average time (note potential error without parentheses) average = runner1 + runner2 + runner3 / 3.0; // Display the average time. averageTimeLabel.Text = average.ToString("n1");
  • The highlighted issue illustrates operator precedence: the division by 3.0 applies only to runner3 in the shown code, not to the sum of all runners.
  • Correct form would be: average=runner<em>1+runner</em>2+runner33.0\text{average} = \frac{runner<em>1 + runner</em>2 + runner_3}{3.0}.

Break Mode

  • In break mode, you can hover the cursor over a variable or a property name in the code editor to inspect its current value.

Autos, Locals, and Watch Windows

  • Autos window: shows variables in the current statement and a few surrounding statements, plus their current values and types.
  • Locals window: shows all variables in the current procedure, with current values and types.
  • Watch window: lets you add variables to monitor; you can open multiple Watch windows.
  • Access these windows via Debug > Windows > [Autos/Locals/Watch].

The Locals Window (example snapshot)

  • Displays current values of local variables in the current scope, including types.

Single-Stepping (1 of 2)

  • Visual Studio can single-step through code after a breakpoint.
  • Steps execute one statement at a time under your control.
  • After each step, you can inspect variable and property values to identify the line causing an error.

Single-Stepping (2 of 2)

  • Ways to single-step:
    • Press F11 (Step Into), or
    • Use the Step Into command on the toolbar, or
    • Debug > Step Into from the menu.

Notes on the code example (Average Race Times) and debugging concepts

  • The example code illustrates parsing input, calculating an average, and displaying the result.
  • It also demonstrates the importance of operator precedence and the usefulness of breakpoints to locate logic errors.

Miscellaneous debugging references

  • Break mode allows inspection of Autos, Locals, and Watches to understand program state at a paused point.
  • The debugger is a critical tool for locating and fixing logic errors during development.