3.1 Reading Input with TextBox Controls 3.2 A First Look at Variables 3.3 Numeric Data Type and Variables 3.4 Performing Calculations 3.5 Inputting and Outputting Numeric Values 3.6 Formatting Numbers with the ToString Method 3.7 Simple Exception Handling 3.8 Using Named Constants 3.9 Declaring Variables as Fields 3.10 Using the Math Class 3.11 More GUI Details


TextBox control Allows user to INPUT a string value into a program. EVERYTHING read IN from a TextBox is a string! EVERYTHING output TO a TextBox is a string!
         string s = txtIn.Text + " goes to town"; // assigns textbox contents to a variable
         lblName.Text = s; // assigns textbox contents to label
- Properties: Text property accepts ONLY string values, e.g. textBox1.Text = "Hello"; - Methods: Clear() Focus() - To clear the content of a TextBox control, assign an empty string("") OR use the Clear method:
         txtIn.Text = "";
To put the focus on the TextBox and highlight the text:
TextBoxes, Strings and Labels  


A variable is a storage location in memory - Variable name represents the memory location - In C#, you must declare a variable in a program before using it to store data - The syntax to declare variables is: DataType VaraibleName;
Data Types - what kind of data is stored - string - int - double - decimal
Variable Names - start with a letter - no spaces - camelCase - name should be meaningful
String Variables - string is a combination of characters - value of a string variable is assigned on the right of = operator surrounded by a pair of double quotes: - productDescription = "Italian Espresso Machine"; - cityName = "Clarion"; TextBox(in/out), Variables, Strings and String Joining  
String Concatenation (Joining) - concatenation is the appending of one string to the end of another string - use "+" operator for concatenation:
         string message;
         message = "Hello " + "World" + "!"; // message gets "Hello World!"
           private void showNameButton_Click(object sender, EventArgs e)
               // Declare a string variable to hold the full name.
               string fullName;

               // Combine the names, with a space between them. Assign the
               // result to the fullName variable.
               fullName = txtFirstName.Text + " " + txtLastName.Text;

               // Display the fullName variable in the fullNameLabel control.
               lblFullName.Text = fullName;

Declaring Variables Before Using Them - MUST declare variables BEFORE using them - multiple variables with the same type may be declared with one statement - can give variables initial value when declaring
       int x, y, z;
       int a=0, b= 1, c=2;
       double d = 5.987;
       decimal price = 77.25m;

Local Variables and Scope and Lifetime and Duplicate Names - a local variable belongs to the method in which it was declared - only statements inside that method can access the variable - class level Variables can be shared among methods! - a variable name can only be used ONCE within a given scope - NO DUPLICATES Scope Code
Assignment Compatibilty and ONE Value at a Time - can ONLY assign values to variables with COMPATIBLE TYPES - a variable holds one value at a time
         string lastName, firstName;
         lastName = "Brown";
         firstName = "Bev";

         string  employeeID;
         employeeID = "125";

         double age, size;
         age = 20.9;
         size = 77;

         int length;
         length = 99;
         length = 122; // 99 is now gone

         decimal cost = 1.25m;
WRITE CODE: Plus Minus Buttons increment/decrement value and display in textbox local variables in each button? fix?


If you need to store a number in a variable and use the number in a mathematical operation, the variable must be of a numeric data type.
Numeric literal: - a numeric literal is an actual number written into your code - NO QUOTES for numeric literals - int: whole number in the range of -2,147,483,648 to 2,147,483,647
         int hoursWorked = 40;
         int count, number;
         count = 0;
         number = count;
- double: real numbers including numbers with fractional parts
         double temperature = 87.6;
         double weight, size;
         weight = 109.5;
         size = weight + 10.5;
- strings do NOT hold numbers...
         string ssn = "123-45-6789"
         string phoneNumber = "815-222-1234";
         string idNumber;
         idNumber = "1234567890";

int: Assignment Compatibility and Explicit Conversion with Cast Operators: int - CAN assign int to int - CAN assign int to double - CAN assign int to decimal - can NOT assign decimal to int - need cast - can NOT assign double to int - need cast
         // numeric literals
         int num = 5;
         double length = 12.75;

         // casts
         num = (int)length; // num will contain 12
         num = (int)cost; // num will contain 99

double: Assignment Compatibility and Explicit Conversion with Cast Operators: double - CAN assign double to double - can NOT assign double to int - need cast - CAN assign int to double
         // numeric literals
         int num = 5;
         double length = 12.75;

         // casts
         length = num; // length will contain 5.0
         length = (double)cost; // length will contain 99.99


Basic calculations such as arithmetic calculation can be performed by math operators "=" is the assignment operator.
      int x; // declare x    
      x = 7; // can be read as x "gets" 7
      int y = -99; // declare  y and y gets -99

Order of Operations Enforced PEMDAS - Multiplication and division before addition and subtraction () parenthesis * multiply / divide % mod (remainder) + add - subtract A math expression performs a calculation and gives a value
         int x = 5, y = 4;
         MessageBox.Show( (x + y).ToString() ); // shows 9

         // follow the order of operations and group with parentheses if necessary
         int x = 3 + 4 * 2; // 11 NOT 14
         int y = (3 + 4) * 2; // 14 NOT 11

Mixed Data Types in Math Expressions - When an operation is performed on two int values, the result will be an int. - When an operation is performed on two double values, the result will be a double. - In a calculation of mixed data type, the data type of the result is determined by: When an operation involves an int and a double, int is treated as double and the result is double When an operation involves an int and a decimal, it is treated as decimal and the result is decimal An operation involving a double and a decimal is not allowed.
         int x = 5;
         double y = 2;
         MessageBox.Show( (x / y).ToString() ); // shows 2.5

Integer Division - When you divide an integer by an integer, the result is ALWAYS an integer.
         int quotient, remain;
         int a = 4, b = 5;
         result = (a + b) / 2; // result is 4 - Quotient
         result = (a + b) % 2; // result is 1 - Remainder

         int x = 7, y = 3;
         MessageBox.Show( (x / y).ToString() ); // shows 2

Combined Assignment Operators: Accumulation += add x += 2; same as x = x + 2;
         int num = 10;
         MessageBox.Show( num.ToString() ); // shows 10

         num = num + 1;
         MessageBox.Show( num.ToString() ); // shows 11

         num += 1;
         MessageBox.Show( num.ToString() ); // shows 12

         num = num + 5;
         MessageBox.Show( num.ToString() ); // shows 17

         num += 3;
         MessageBox.Show( num.ToString() ); // shows 20


Input collected from the keyboard are considered combinations of characters (or string literals) even if they look like a number to you.
Getting a Number from a TextBox EVERYTHING read in from a TextBox is ALWAYS read in as a string!!! A TextBox control reads keyboard input, such as 25.65. However, the TextBox treats it as a string, not a number. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the following Parse methods to convert string to numeric data types int.Parse double.Parse
            int hoursWorked = int.Parse(txtHours.Text);
            double temperature = double.Parse(txtTemp.Text);
            string s = txtCity.Text; // NO parse needed

FROM FROM FROM double int string ------------------------------------- TO double - * * double.Parse() - TO int - (int) * int.Parse() - TO string - ToString() ToString() * * = no conversion needed
Displaying Numeric Values and Explicit Conversion - To display a number requires you to convert numeric data to string type - can NOT display a number in the Text property of a control - can NOT display a number using MessageBox.Show() - ToString() converts a number or numeric variable to a string
         int myNumber = 123;
         MessageBox.Show( myNumber.ToString() );

         double grossPay = 1550.0;
         lblgrossPay.Text = grossPay.ToString();

         double area = 789.765;
         txtOut.Text = area.ToString();
Fuel Economy (int, decimal, convert, math)   Test Average (textBoxes, convert, math, clear)  
Displaying Numeric Values and Implicit Conversion - the "+" operator is both an addition AND a string join operator (overloaded operator)
         "The answer is " + 7; // converts the number 7 to a string implicitly
         // implicit string conversion with the + operator:
         int idNumber = 1044;
         string output = "Your ID number is  " + idNumber; // implicit conversion
         MessageBox.Show( "My weight is " + 168 ); // implicit conversion
         double number = 9876.8;         
         MessageBox.Show( "Number is " + number ); // implicit conversion
         double m = 8.9;
         double d = 7.8;
         MessageBox.Show(d + "Answer is " + d + m); // 7.8Answer is 7.88.9
Explicit and Implicit Conversion: Add 2 integers? strings?


The ToString method can optionally format a number to appear in a specific way The following lists the "format strings" and how they work with sample outputs ToString("N"); // number with thousand separator and 2 decimal places ToString("N3"); // number with thousand separator and 3 decimal places ToString("N0"); // number with thousand separator and 0 decimal places ToString("C"); // currency ToString("P"); // percentage Sale Price Calc (decimal variable, parse, math)   Wage Calculator (IPO)  


An exception is an unexpected error that occurs while a program is running, causing the program to halt if the error is not properly dealt with. Exceptions are usually caused by circumstances that are beyond the programmer’s control. - exception handler try { code to protect } catch { error handling code } - exception handler with reporting try { code to protect } catch (Exception ex) { error handling code use ex.Message } About Exceptions - try catch Add 2 integers from textboxes (try catch)   w/comments Test Average (try-catch) Fuel Economy (try-catch) Invoice Total with Accumulation(try-catch


A number constant is a name that represents a value that cannot be changed during the program's execution. Self-documenting. Upper case by convention. In C# a constant can be declared by const keyword
      const double INTEREST_RATE = 0.129;
      const int HiGH_SCORE = 100;  
Accumulators & Initialization  


Declare fields at the top of a class. A field is NOT contained in a method - A field is a variable that is declared at the class level. A field’s scope is the entire class. Its lifetime is the life of a program. - A local variable is declared IN a method. The scope is ONLY IN the method. Its lifetime is the life of the method. Field & Scope & Lifetime Demo (strings)


The .NET Framework’s Math class provides several methods for perform- ing complex mathematical calculations. Math Class Method Description Math.Abs( x ) Returns the absolute value of x . Math.Ceiling( x ) Returns the least integer that is greater than or equal to x (a decimal or a double ). Math.Floor( x ) Returns the greatest integer that is less than or equal to x (a decimal or a double ). Math.Max( x , y ) Returns the greater of the two values x and y . Math.Min( x , y ) Returns the lesser of the two values x and y . Math.Pow( x , y ) Returns the value of x (a double ) raised to the power of y (also a double ). The value that is returned is a double . Math.Sqrt( x ) Returns the square root of x (a double ). The value that is returned is a double .


Tab Order View Tab Order Focus Keyboard Access Keys & before the key (alt) Accept Button (form) Enter Cancel Button (form) ESC BackColor ForeColor GroupBoxes Panels

SandBox ♥ Reference: building blocks properties, methods & events lifetime & scope button, textBox, label pictureBox, MessageBox variables & arithmetic