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
- 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 (or ): e.g. .
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. .
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 and , the int is treated as a double and the result is .
- If an operation involves and , the int is treated as and the result is .
- An operation involving a and a 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 for some integer division.
- To avoid integer division, promote at least one operand to a floating point type (e.g., cast to or use a 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 but treats it as a string.
- Use Parse methods to convert string to numeric types:
- , ,
- 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 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
- →
- Fixed-point: →
- Exponential/scientific: →
- Currency: → e.g. ($1,234,567.80)
- Percentage: → e.g.
- 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 statement:
- The block contains statements that could throw exceptions.
- The 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 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 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:
- returns the square root of (a ).
- returns ; both and are .
- Predefined constants:
- represents the ratio of a circle's circumference to its diameter.
- 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 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 .
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: .
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.