Last Modified 5-1-2010

IUSB

Home

C#


Introduction to C#

.NET Framework

VS2008 IDE

How C# is Compiled

Start Visual Studio


Windows Form App


C# OOP Coding

C# Code Example


C# Coding Rules

Recommendations

Error Window

C# Comments

C# Help Window

Language Essentials

C# Data Types

Declare Variables

Declare Constants

Arith. Expressions

Assign Statements


Operator Precedence

Type Casting

Math Class

C# Strings

String Esc Sequences

Convert Data Types


ToString Formatting

Variable Scope Use

C# Enumeration Use

C# Nullable Types

Program #2


C# Code Control

Relational Operators

Logical Operators

If-Else Statement

Switch Statement


Introduction to C# Object Oriented Programming

Whether you realize it or not, you are using object-oriented programming as you design a Windows form with Visual Studio's Form Designer. That's because each control on a form is an object, and the form itself is an object. These objects are derived from classes that are part of the .NET Class Library.

When you start a new project from the Windows Application template, you are actually creating a new class that inherits the characteristics of the Form. The Form, in turn, is part of the .NET Class Library. Later when you run the form, you are actually creating an instance of your form class, and this instance is known as an object.

Similarly, when you add a control to a form, you are actually adding a control object to the form. Each control is an instance of a specific class. For example, a text box control is an object that is an instance of a specific class. For example, a TextBox control is an object that is an instance of the TextBox class. Similarly, a label control is an object that is an instance of the Label class. This process of creating an object from a class can be called instantiation.

As you progress through this guide, you will become more familiar with classes and objects because C# is an object-oriented language. Later we will actually create classes. At that point, we can start to understand what is happening as we work with classes and objects. For now, we will just get comfortable with the terms and concepts and understand that a lot is going on behind the scenes, and we will begin to understand those processes as we progress through this guide.

To help illustrate this concept observe the following diagram:

Form Only

Class and Object Concepts

  • Object: Self-Combined unit that combines code and data.
    • Examples: Forms and Controls.
  • Class: Code that defines the characteristics of the object.
    • A Class is a template for the object.
      • TextBox Icon in Toolbox is a class.
      • TextBox becomes an object as we set the properties.
  • Instance of a class: When the class icon becomes an object.
  • One or more instances can be created from a class.
    • Each TextBox on our Form is an instance of the TextBox class.
    • Each TextBox shares characteristics (class) but they are unique (object).

Property, Method and Event Concepts

  • Property: Defines the characteristics of an object and the data associated with it.
  • Method: Operations the object can perform.
  • Event: Signal sent by the object to the program telling that something has happened.
    • Examples: Mouse Move, Mouse Key Press, Keyboard Key Press
  • Members: Properties, Methods and Events of an object.
  • When two or more instances of an object are instantiated (created) from the same class, they all have the same properties, methods and posssible events. However, the values that we assigned to each object were slightly different.

Objects and Forms

  • When you use the Visual Studio C# 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 set's 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.

Figure CS-25: C# Class, Object, Property, Method and Event Concepts



Adding Code to the Invoice Total Form

Make sure that the Invoice Total program has been terminated by pressing the Red 'X' at the top right of the form. Select the Form1.cs[Design]* tab and double-click on the Exit button as indicated in the diagram below:

Double Click Exit

Figure CS-26: Select C# Form1 Design and double-click Exit Button


Double-Clicking the Exit Button will bring up the source code window. All the code referencing the InvoiceTotal Form is contained on this page. The following diagram shows the contents of the Source Code Window:

Exit Button Code Template

Figure CS-27: C# Source Code Template for Exit Button



Place the cursor between the Curly Braces at the point where Figure CS-27 says:Enter Code Here by clicking the mouse pointer at that location. Enter the letter 't' at that location. This will bring up the Microsoft Visual Studio completion list as indicated in the diagram below:

Completion List this

Figure CS-28: Visual Studio C# Completion List - this Highlighted


When you enter the 't' the completion list may highlight the word this which is the word we wish to enter at this point. C# Visual Studio attempts to guess at the word you need next based on your previous programming techniques as well as the most likely response under the current situation. If this is not highlighted, you have two choices:

  • Continue typing 'h' 'i' and 's' until the completion list figures out which word you want, or:
  • Move the up/down arrows until the word this is highlighted.
    • The completion list is in alphabetical order, so it may be better to type in another letter or two.

It is best to use the completion list whenever possible because it will reduce syntax errors and help make the proper Object Oriented programming statement for the task you are trying to accomplish. This is very important in an almost 4G level language like the .NET Framework.

In C#, when referring to the current Form, it is customary to use the keyword this to identify the Form. The task we wish to accomplish with the Exit Button is to close the current Form and terminate the program. The one-line statement in C# that will accomplish this task is:

this.Close();

The Exit function when completed should look like the following diagram:

This Dot Close

Figure CS-29: Completed Exit Function using this.Close()



I don't know about you, but I am chomping at the bit to try out this C# Object Oriented Program with Class functionality on a Visual Studio .NET Framework software development project. Whew, that was a mouthful. I would personally rather just say I hacked a couple of lines of C# code, but that might not impress some prospective employer, so we'll go either way, depending on who we are talking to at the moment. Press the green triangle Start Debugging Symbol to start the program execution with some functional C# code and see what we get. But this time, let's press the Exit Button, , we placed on the Form instead of the Red X to terminate the program:

Looks like it works just like those clever software developers @ Microsoft planned. The <esc> key seems to work just fine too. Remember, we told .NET that the cancel or esc key was to act as a button press on the button?

We are now going to move towards obtaining functionality with the button. Putting in error checking and validation at this point, just makes it more difficult to get a clear understanding of some of the underlying concepts, so we are going to hold off on that for a moment, and just enter data into the Subtotal TextBox:

Subtotal:

manually and in the correct format.


When we press the calculate button we want the following events to occur:

  • Suck the data out of the Subtotal TextBox and get the numeric equivalent.
    • Subtotal:
  • Set a default value of 10% for the DiscountPercent
    • DiscountPercent=.1;
  • Mulitply the Subtotal by the DiscountPercent to get a DiscountAmount.
    • DiscountAmount = Subtotal * DiscountPercent;
  • Display the Value of 10% in the DiscountPercent TextBox (txtDiscountPercent).
    • Discount Percent:
  • Display the DiscountAmount in the DiscountAmount TextBox (txtDiscountAmount)
    • Discount Amount:

Press the Form1.cs[Design] tab to bring up the graphical view of the Design Form. Place the mouse pointer over the button and double-click to bring up the source code window, and creating the Calculate Button Click-Event template. Enter the code as indicated in the diagram below, using the code completion list as much as possible to reduce programmer errors:

Calculate Code 1

Figure CS-30: C# Source Code for Invoice Total Calculate Button Version 1



Let's take a quick look at the statements in this Method:

  • private void btnCalcuate_Click: Event generated by .NET Framework to respond to Mouse-Click or <ENTER> key.

  • double Subtotal=Convert.ToDouble(txtSubtotal.Text);
    • double: A common numeric datatype in C# is type double.
      • All objects declared in C# must have a datatype associated with them.
      • TextBoxes have letters or characters representing numbers in them.
        • Characters may represent numbers but they are not numbers.
        • The characters must be converted to their numeric equivalent before they can be treated as a number.
      • The double datatype represents positive and negative numbers with decimal points.
        • The largest number type double can represent is around 1.8 x 10308.
        • The smallest number type double can represent around 5.0 x 10-324
        • So pretty much most of the numbers in everyday casual conversation can be represented by type double.

    • Subtotal=: This is the name we have given to the numeric variable which holds the Subtotal value.

    • Convert:This is a Method of datatypes in C# so we can convert between the different types.
      • C# requires that when we perform operations on variables that they usually be of the same datatype.
        • You can add 3 apples to 2 apples to get 5 apples.
        • But, you can't add 3 apples to 4 airplanes and have it make any sense.
        • Though, with object C# oriented programming you could add the apples on the plane to the apples in your fruitbasket, and that could make sense.

    • ToDouble: This is the datatype we have decided to work with, though we could have worked floats or decimal as well.

    • (txtSubtotal.text): This refers to the data entered in the TextBox field by the User.

  • double DiscountPercent=.1; Variable we are using to keep track of the discount on the Subtotal.
    • We are setting the default value to 10% for this example.

  • double DiscountAmount = Subtotal * DiscountPercent; Declaration of variable DiscountAmount
    • Calculated as the Subtotal multiplied by the DiscountPercent amount.

  • txtDiscountPercent.Text = DiscountPercent.ToString("p1"); Updates the Discount Percent TextBox on the Form.
    • txtDiscountPercent.Text=: Refers to the text the user sees in the Discount Percent TextBox.
    • DiscountPercent: This is the numeric value that will be displayed in the TextBox.
    • .ToString: .NET Framework Method to convert Numeric values into a text representation.
    • ("p1"): Instructs the .NET Framework to make a Percent (the p) with 1 place to the right of the decimal.

  • txtDiscountAmount.Text = DiscountAmount.ToString("c"); Updates the Discount Amount TextBox on the Form.
    • txtDiscountAmount.Text=: Refers to the text the user sees in the Discount Amount TextBox.
    • DiscountAmount: This is the numeric value that will be displayed in the Textbox.
    • .ToString: .NET Framework Method to convert Numeric values into a text representation.
    • ("c"): Instructs the .NET Framework to make a Currency('$') value with 2 places to the right of the decimal.


We are now going to test our code by following the steps below:

  • Press the Start Debugging Start Debugging Symbol symbol.

  • Enter the value 100 in the Subtotal TextBox: Subtotal TextBox

  • Press the <ENTER> key on your keyboard or the Calculate Button button.

Performing the above steps should result in program output as indicated in the diagram below:

Invoice Total Runtime1

Figure CS-31: C# Program Invoice Total At Runtime Ver1


Now that we have some familiarity with integrating C# code with .NET Framwork Forms. We are ready to expand the requirements of pressing the Calculate Button button. Pressing the Calculate button should give us the following procedure:

  • Value entered into Subtotal TextBox is transferred to the variable Subtotal.
    • double Subtotal=Convert.ToDouble(txtSubtotal.Text);

  • Determine DiscountPercent from the following requirements:
    • If Subtotal >=500 then DiscountPercent=20%.
    • If Subtotal<500 and Subtotal>=250 then DiscountPercent=15%.
    • If Subtotal<250 and Subtotal>=100 then DiscountPercent=10%.
    • Otherwise, DiscountPercent=0%.

  • Multiply the Subtotal by the DiscountPercent to get a DiscountAmount.
    • DiscountAmount=Subtotal*DiscountPercent;

  • Subtract the DiscountAmount from the Subtotal to get the InvoiceAmount.
    • InvoiceAmount=Subtotal-DiscountAmount.

  • Display the DiscountPercent in the DiscountPercent TextBox.
    • txtDiscountPercent.Text=DiscountPercent.ToString("p1");

  • Display the DiscountAmount in the DiscountAmount TextBox.
    • txtDiscountAmount=DiscoutAmount.ToString("c");

  • Display the InvoiceTotal in the InvoiceTotal TextBox.
    • txtInvoiceTotal = InvoiceTotal.ToString("c");

  • Set the Focus back to the Subtotal TextBox.
    • txtSubtotal.Focus();