Breaking News

Events In C#

A C# event is a class member that is activated whenever the event it was designed for occurs. I like to use the term “fires” when the event is activated. Anyone interested in the event can register and be notified as soon as the event fires. At the time an event fires, registered methods will be invoked.
 
Events and delegates work together to provide a program’s functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event.
 
The delegate may be one of the pre-defined .NET delegates or the delegate you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires. The general syntax of any event is:
 
[Access Modifier] event delegatename eventname;
 
For Example
 
public delegate void newdelegate(); //Delegate Declaration
public event newdelegate newevent; //Event Declaration
 
We can categories event into two parts:
 
? Customize Events
? Predefined Events
 
Customized Events
 
Don’t confuse these terms because I have categorized events so that the explanation become simple. Now what do we mean by customize events, they are events which we define according to our needs and are not defined. previously or it is not a system defined events. Suppose that if we want to raise an event whenever a dynamic control is created on the form.
 
To declare an event, first define the delegate for that event, if none is already declared. The delegate type defines the set of argument that are to be passed to the method which will act as event handler.
 
Example
 
namespace Eventhandling
   { 
     public delegate void IamClicked(); 
    
     /// <summary>
     /// Summary description for Form1.
     /// 
     public class Form1 : System.Windows.Forms.Form
     {
       /// <summary>
       /// Required designer variable.
       /// 
       private System.ComponentModel.Container components = null;
       public System.Int32 o_IntCounter=0;
       public event IamClicked ClickMe;
       System.Int32 o_intXaxis=120;
       System.Int32 o_intYaxis=80;
   	   
       public Form1()
       {
         //
         // Required for Windows Form Designer support
         //
         InitializeComponent();
         //
         //TODO:Add any constructor code after InitializeComponent call
         //
         Button b1=new Button();
         b1.Parent=this; 
         b1.Location=new Point(o_intXaxis,o_intYaxis);
         b1.Name="Click1";
         b1.Text="Click Me";
         ClickMe+=new IamClicked(Show);
         ClickMe(); 
       }

     /// <summary>
     /// Clean up any resources being used.
     /// 
     protected override void Dispose( bool disposing )
     {
       if( disposing )
       {
         if (components != null) 
         {
           components.Dispose();
         }
       }
       base.Dispose( disposing );
     }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor
    /// 
    private void InitializeComponent()
    {
      // 
      // Form1
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(304, 237);
      this.Name = "Form1";
      this.Text = "Events";
	}
	#endregion

    /// <summary>
    /// The main entry point for the application.
    /// 
    [STAThread]
    static void Main() 
    {
      Application.Run(new Form1());
    }
    /// <summary>
    /// Event Handler Function Which is called when the 
    /// Click Event is Raised.
    /// 
    /// <param name="o">
    /// <param name="ea">
    public void Show()
    {        
       MessageBox.Show("JUST BORN");   
    }
  }
}
 
The above program shows how we can fire our own events. In this program a button is created dynamically.
 
Button b1=new Button();
    b1.Parent=this; 
    b1.Location=new Point(o_intXaxis,o_intYaxis);
    b1.Name="Click1";
    b1.Text="Click Me";
    ClickMe+=new IamClicked(Show);
    ClickMe(); 
 
The delegate and event defined in above program are:
 
public delegate void IamClicked();
public event IamClicked ClickMe;
 
The delegate points to the following function.
 
    public void Show()
    {        
      MessageBox.Show("JUST BORN");   
    }
 
When the ClickME event is fired the delegate attached to this event call the above function Show. Look at the signature of the function and the delegates both are same. The function just shows a message box with the message “Just Born”.
 
Predefined Events
 
Events and delegates go hand in hand. Now we are considering Predefined events like
 
? Click Event
? DoubleClick Event
? MouseOver Event
? Closed Event
? Closing Event
? DragDrop Event
? Enter Event
? Load Event
? Leave Event etc.
 
We normally use predefined events in our programming practice. Multiple events can share the same delegate type. The event is declared as the delegate type. In C# we must follow specific signature for Handler.
 
void OnClick(object o,EventArgs ea)
{
//Code
}
 
Example
 
using System;
   using System.Drawing;
   using System.Collections;
   using System.ComponentModel;
   using System.Windows.Forms;
   using System.Data;

   namespace Eventhandling
   {
     /// <summary>
     /// Summary description for Form1.
     /// 
     public class Form1 : System.Windows.Forms.Form
     {
       /// <summary>
       /// Required designer variable.
       /// 
       private System.ComponentModel.Container components = null;
       public System.Int32 o_IntCounter=0;
       private System.Windows.Forms.Button btnNewControl;
            
       public Form1()
       {
         //
         // Required for Windows Form Designer support
         //
         InitializeComponent();
         //
         //TODO:Add any constructor code after InitializeComponent call
         //
       }

       /// <summary>
       /// Clean up any resources being used.
       /// 
       protected override void Dispose( bool disposing )
       {
         if( disposing )
         {
           if (components != null) 
           {
             components.Dispose();
           }
         }
         base.Dispose( disposing );
       }

       #region Windows Form Designer generated code
       /// <summary>
       /// Required method for Designer support - do not modify
       /// the contents of this method with the code editor
       /// 
       private void InitializeComponent()
       {
         this.btnNewControl = new  System.Windows.Forms.Button();
         this.SuspendLayout();
         // 
         // btnNewControl
         // 
         this.btnNewControl.Name = "btnNewControl";
         this.btnNewControl.Size = new System.Drawing.Size(112, 32);
         this.btnNewControl.TabIndex = 0;
         this.btnNewControl.Text = "New Control";
         this.btnNewControl.Click += 
new System.EventHandler(this.btnNewControl_Click);
         // 
         // Form1
         // 
         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
         this.ClientSize = new System.Drawing.Size(304, 237);
         this.Controls.AddRange(new System.Windows.Forms.Control[] 
         {
           this.btnNewControl});
           this.Name = "Form1";
           this.Text = "Events";
           this.ResumeLayout(false);
         }
         #endregion

         /// <summary>
         /// The main entry point for the application.
         /// 
         [STAThread]
         static void Main() 
         {
            Application.Run(new Form1());
         }

         /// <summary>
         /// Event Handler Function Which is called when the 
         /// Click Event is Raised.
         /// 
         /// <param name="o">
         /// <param name="ea">
         public void btnAdd(object o,EventArgs ea)
         {
           o_IntCounter++;
           MessageBox.Show(o_IntCounter.ToString());   
         }

         private void btnNewControl_Click(object sender, System.EventArgs e)
         {
         System.Int32 b_intCount;
         System.Int32 b_intXaxis=120;
         System.Int32 b_intYaxis=80;
         for(b_intCount=1;b_intCount<=3;b_intCount++,b_intYaxis+=20)
         {
           ///new buttons are created at run time
           ///with there location and names.
           Button b1=new Button();
           b1.Parent=this; 
           b1.Location=new Point(b_intXaxis,b_intYaxis);
           b1.Name="Click1"+b_intCount; 
           b1.Text="Click Me";
           b1.Click+=new EventHandler(btnAdd);   
         }
       }
    }
}
 
In the above program, we create three buttons at run time and when any of the buttons is clicked the Click event of that button is fired.
 
for(b_intCount=1;b_intCount<=3;b_intCount++,b_intYaxis+=20)
{
   ///new buttons are created at run time
   ///with there location and names.
   Button b1=new Button();
   b1.Parent=this; 
   b1.Location=new Point(b_intXaxis,b_intYaxis);
   b1.Name="Click1"+b_intCount; 
   b1.Text="Click Me";
   b1.Click+=new EventHandler(btnAdd);   
}
 
The Click event belongs to the button class. We will reference it when we are registering a delegate.
 
b1.Click+=new EventHandler(btnAdd);
 
The delegate EventHandler is also defined in the System namespace of Dot net Framework library. All what we have to do is to define our callback function that is invoked when the button is clicked and accepts two arguments object and EventArgs type conforms the signature of delegate EventHandler defined in System namespace.
 
public void btnAdd(object o,EventArgs ea)
{
  o_IntCounter++;
  MessageBox.Show(o_IntCounter.ToString());   
}
 
The handler btnAdd() Method catches this event and shows a message box that indicates a number that how many times these buttons are clicked. The above example is quite self explanatory so just copy the code in a new project and run for yourself.
 

Check Also

Errors in C#

There are three types of errors in C# that can be occur in your application. …