C#: Introduction to Event Handling

Author: Ronald S. Holland
Total Application Works

To contact us

HOME Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2014 All Rights Reserved Total Application Works

    Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
    <title>C#: Table of Contents </title>
    <a href="http://sumtotalz.com/TotalAppsWorks/CSharp/CS_Event_Handling.html">
    Event Handling </a>

Table of Contents

  1. Attributes
  2. Introduction to C#
  3. Selection Construct in C#
  4. Loops Construct
  5. Methods
  6. Namespaces
  7. Introduction to Classes:
  8. Inheritance:<
  9. Polymorphism
  10. Properties
  11. Indexers
  12. Structs
  13. Interfaces
  14. Delegates:
  15. Event Handling ">
  16. Exception Handling:
  17. Enums
  18. Encapsulation
  19. Parameter Passing in C#
  20. Method Overloading
  21. Database Interaction Using C#
  22. Operator Overloading in C# -1
  23. Operator Overloading in C# -2
  24. Operator Overloading in C# -2
  25. Sockets
  26. DNS [Domain Name System]
  27. Working with Files
  28. Generating Help File in C#
  29. Code Access Security
  30. Multi-Threading
  31. Globalization and Localization -1
  32. Working with Registry in C#
  33. Globalization and Localization -2
  34. Windows Service
  35. Web Service
  36. Consuming Web Services
  37. Creating Proxy Object of Web Service
  38. Creating an XML document
  39. Reading XML document in C#
  40. Using XMLWriter class to Write XML document in C#
  41. Assembly Information :
    Getting Permission set of the assembly
  42. Creating your own Permission Set
  43. Using C# Socket

Objectives of this tutorial

After you have completed this tutorial, you should:

  • Understand the basic C# event handling programming.
  • Learn more about what a Main method does.
  • Learn about console input/output (I/O).

Read Me First

The BForm.zip compressed file contains the following seven projects:

  1. Form1.cs
  2. Blank_Form.VSROJ
  3. Form1.Designer.cs
  4. Program.cs
  5. BForm.zip
  6. CS_Event_Handling.html
To run the project:
  1. Save
  2. Go to the folder where you downloaded the BForm.zip compressed file
  3. Extract the files
  4. Right click on one of the Blank_Form.VSROJ - click on the version of Microsoft studio you have
  5. When Microsoft studio IDE is started
  6. Click on the Debug menu
  7. Click on the Start without Debugging menu item
    • The Blank_Form.VSROJ will begin to execute
  8. Copy BForm.zip to another folder called template for future use.

Introduction to C# - Event Handler

The purpose of this tutorial is to introduce you to the basics of C# ("C sharp") event handling. Even if you've never programmed in a language similar to C/C++ or Java before, this tutorial should be very easy to follow and understand. It assumes that you have some basic exposure to programming (some object-oriented experience would be helpful, but is not necessary) and you have some kind of C# compiler (if you would like to run the examples). First, you should know that C# is a language designed by Microsoft. It is intended to combine the most significant parts of C/C++ along with the productivity of a 4GL, such as Visual Basic. This tutorial assumes you have read and mastered the following:

  1. Introduction to C#
  2. c#: Introduction to FormsIntroduction to Forms

What is a program event? In real life, we experience some of the following events every day. For example:

  1. We ring a doorbell (event)
      Someone does or does not respond
  2. We toggle the light switch (event)
      the light(s) come on or go out
  3. The telephone rings (event)
      we either pick up and say hello or we allow the answering machine to take a message
  4. We push the power-on button on the remote control (event)
      the TV comes on or goes off
  5. We turn the car ignition key or push the start button (event)
      The car starts or does not start
  6. The traffic light turns red (event)
      drivers brake to a stop
For each of the above events, there is a possible response. In c# programming, for each event we provide a method with the possible responses we want the program to handle.

You will need a c# compiler to run the examples in this tutorial. If you do not have a C# compiler, instructions on how to obtain one will be described in the next section.

Free Compilers

you can download a free copy at Microsoft's 2010 Visual Studio Downloads Page or Microsoft's 2012 Visual Studio Downloads Page. This download may take approximately 24 hours using a 56 kbps dial-up, If you don't have a c# compiler, You may be able to download a copy in 5-10 minutes, if you have access to a T1 line at a public college or a public library, assuming a line is available. You may be able to download a copy in 15-20 minutes, if you have access to a broadband internet provider. You can follow the steps below:

  1. Download a free copy of VC# at Microsoft's Visual Studio Downloads Page.
    • This copy is in image file format (ISO images).
    • I used this option: All - Offline Install ISO image file. With this option, you get the following:
      • Visual Basic 2010 Express Edition
      • Visual C# 2010 Express Edition
      • Visual C# 2010 Express Edition
      • Visual Web Developer 2010 Express Edition
  2. Download a free copy of VCdControlTool. It only works with ISO images. Installation instructions:
    1. Copy VCdRom.sys to your WINDOWS\system32\drivers folder.
    2. Execute VCdControlTool.exe
    3. Click "Driver control"
    4. If the "Install Driver" button is available, click it. Navigate to the WINDOWS\system32\drivers folder, select VCdRom.sys, and click Open.
    5. Click "Start"
    6. Click OK
    7. Click "Add Drive" to add a drive to the drive list. Ensure that the drive added is not a local drive. If it is, continue to click "Add Drive" until an unused drive letter is available.
    8. Select an unused drive letter from the drive list and click "Mount".
    9. Navigate to the image file (VS2010ExpressWithSP1ENUX1504728.iso or VS2010Express1.iso), select it, and click "OK". UNC naming conventions should not be used; however, mapped network drives should be OK.
  3. Next use Windows Explorer to navigate to the Virtual drive you mounted. You will see the following folders:
    • Include
    • VBExpress
    • VCExpress
    • VCSExpress
    • VWDExpress
  4. Use the setup application in each folder to install the desired components.
  5. You are ready to start programming.
  6. You can download other compilers at:
    1. free +c# +IDE
    2. c# IDE


There are 23 buttons in the above c# calculator Form application. Each of the buttons causes an event when clicked. The program then performs some pre-defined operation and either exits or returns to the original point-of-focus that caused the previous event. Modern GUI programs operate on an event-based model. That is, some event in the program occurs and methods linked to the event are notified so they can react appropriately. With Windows Forms, there is an asynchronous mechanism is all built into the system with events.

A C# event handler is a class method that is called whenever the event it was designed for occurs. I like to use the term "asynchronously called" when the event is activated. When one of the 0 through 9 and decimal point buttons is clicked, the text representation of that button is entered into the input box.

Basic Calculator
Figure 1: Basic Calculator

Declaring and Implementing Events

The following table shows a partial outline for how to start filling in your event handler code.

 namespace BasicCalc {

    * The onClick() method is an event handler that responds to mouse click events.
            .     <--------- pseudocode

   private void onClick(object event_key, EventArgs e) {
            .     <--------- pseudocode

      // This code is repeated fot buttons 1 - 9 and button point      
      if (event_key == "0") {  // btn0 clicked
         InputBox.Text = "0";
            .     <--------- pseudocode
      // This code is repeated fot buttons 1 - 9 and button point 
      // to capture event when numlock is clicked 
      if (e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0) { 

         InputBox.Text = "0";
            .     <--------- pseudocode 

            .     <--------- pseudocode
            else if (event_key == btnPlus) { 
                 getSolution();  oper = '+'; }           //Plus button clicked
            else if (event_key == btnMinus) { 
                 getSolution();  oper = '-'; }           //Minus button clicked
            else if (event_key == btnMultiply) { 
                 getSolution();  oper = '*'; }           //Multiply button clicked
            else if (event_key == btnDivide) { 
                 getSolution();  oper = '/'; }           //Division button clicked
            else if (event_key == btnEqual) { 
                 Clear();                           //Equal button clicked
                 equal = true; }
            else if (event_key == btnPlusMinus)        //PlusMinus button clicked
                num3 = Convert.ToDouble( InputBox.Text ) ;
                num3 = num3 * -1.0 ;
                InputBox.Text = Convert.ToString( num3 ) ;     //Convert num1 into  text

            else if (event_key == btnBack)             //Back button clicked
                if (InputBox.Text.Length >= 1)
                    InputBox.Text = 
                           InputBox.Text.Substring(0, (InputBox.Text.Length) - 1);
                    if (InputBox.Text.Length == 0 )
                       InputBox.Text = "0" ;
            else if (event_key == btnClear) {        //Clear button clicked
                     InputBox.Text = "0"; } 
            .     <--------- pseudocode
Figure 2: Event Handler pseudocode snippet

Adding a button to the Windows Forms application is simple. You can add a button member to the class, initialize it in the constructor, and place it in the controls collection.


        private void InitializeComponent()
            System.ComponentModel.ComponentResourceManager resources = 
                    new System.ComponentModel.ComponentResourceManager(typeof(BasicCalc));
            this.InputBox = new System.Windows.Forms.Label();
            this.btnPoint = new System.Windows.Forms.Button();
            this.btn0 = new System.Windows.Forms.Button();
            this.btn1 = new System.Windows.Forms.Button();
            this.btn2 = new System.Windows.Forms.Button();
            this.btn3 = new System.Windows.Forms.Button();
            this.btn4 = new System.Windows.Forms.Button();
            this.btn5 = new System.Windows.Forms.Button();
            this.btn6 = new System.Windows.Forms.Button();
            this.btn7 = new System.Windows.Forms.Button();
            this.btn8 = new System.Windows.Forms.Button();
            this.btn9 = new System.Windows.Forms.Button();
            this.btnEqual = new System.Windows.Forms.Button();
            this.btnMinus = new System.Windows.Forms.Button();
            this.btnMultiply = new System.Windows.Forms.Button();
            this.btnDivide = new System.Windows.Forms.Button();
            this.btnClear = new System.Windows.Forms.Button();
            this.btnPlus = new System.Windows.Forms.Button();
            this.btnPlusMinus = new System.Windows.Forms.Button();
            this.btnSQRT = new System.Windows.Forms.Button();
            this.btnBack = new System.Windows.Forms.Button();
            this.btnOFF = new System.Windows.Forms.Button();
            this.btnabout = new System.Windows.Forms.Button();
            this.btnHelp = new System.Windows.Forms.Button();
            this.bCopy = new System.Windows.Forms.Button();
            this.bSquare = new System.Windows.Forms.Button();
            // InputBox
            this.InputBox.BackColor = System.Drawing.Color.White;
            this.InputBox.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.InputBox.Cursor = System.Windows.Forms.Cursors.IBeam;
            this.InputBox.Font = new System.Drawing.Font("Arial", 15.75F, 
                    System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.InputBox.Location = new System.Drawing.Point(27, 9);
            this.InputBox.MaximumSize = new System.Drawing.Size(278, 35);
            this.InputBox.MinimumSize = new System.Drawing.Size(278, 35);
            this.InputBox.Name = "InputBox";
            this.InputBox.Size = new System.Drawing.Size(278, 35);
            this.InputBox.TabIndex = 0;
            this.InputBox.Text = "0";
            this.InputBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // btnPoint

            // btn0
            .     <--------- button declaration
            // btn9
            .     <--------- button declaration
            // btnSQRT
            this.btnSQRT.Font = new System.Drawing.Font("Arial", 8.75F, System.Drawing.FontStyle.Bold);
            this.btnSQRT.Location = new System.Drawing.Point(310, 192);
            this.btnSQRT.Name = "btnSQRT";
            this.btnSQRT.Size = new System.Drawing.Size(55, 33);
            this.btnSQRT.TabIndex = 0;
            this.btnSQRT.TabStop = false;
            this.btnSQRT.Text = "SQRT";
            this.btnSQRT.UseVisualStyleBackColor = true;
            this.btnSQRT.Click += new System.EventHandler(this.btnSQRT_Click);

Figure 3: Declaring buttons code snippet

Creating buttons and a textbox

To create buttons:

  1. Go to the right side of the Visual Studio IDE;
  2. Click on the Toolbox tab/button;
  3. Click on the All Window Forms;
  4. Click on the Button;
  5. Click on the All Window Forms;
  6. Click on the Textbox;

When this is done, you can link an event that is captured whenever the button is clicked. An event handler is a method that is bound to an event. When the event occurs, the code within the event handler is executed. Each event handler provides two parameters that allow you to handle the event properly.

HOME Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

To contact us

© 2002 - 2014 All Rights Reserved Total Application Works