Monday, 6 January 2014

Event Handling in .Net using C#

Event Handling in .Net using C#

Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface. A single event handler can be used to process events raised by multiple controls. An event can be associated with multiple event handlers, which will be invoked synchronously when the event occurs. Event handlers can also be used to handle events that signal an object's state changes to the object's clients.
An event handler, in C#, is a method that contains the code that gets executed in response to a specific event that occurs in an application.
How to work on Event in C# .Net 
             
Setp 1: Create a delegate based handler or function

 Access Specifier return type Name of function

Like:  we create   functions……………………………………………………….

public void function()
{
MessageBox.Show("We are Handler");
}

public void function1()
{
MessageBox.Show("We are Handler1");
}

Setp 2: After than we create delegate for above function

 Access Specifier delegate return type  Name of delegate in form of  function
  
  public delegate void MyEventDel();
         
Setp 3: create an event using delegate

Access Specifier event Name of delegate Name of Event

public event MyEventDel myevent;

Setp 4: After Procedure to registered function or handler with Event

myevent = myevent + function;
myevent = myevent + function1;


Setp 5Procedure to fire an event……………
            myevent();

Pictorial representation of Event Handling in C# .Net



Example with C# .Net……………………….

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EventHanding
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{

}
//Step-1 create a delegate based function and Handler.........
public void function()
{
MessageBox.Show("We are Handler");
}
public void function1()
{
MessageBox.Show("We are Handler1");
}
//Step-2 After than we create delegate for above function
public delegate void MyEventDel();
//Step- 3 create an event using delegate
public event MyEventDel myevent;

private void button1_Click(object sender, EventArgs e)
{
// Setp 4: After Procedure to registered function or handler with Event
   myevent = myevent + function;
   myevent += function1;
//Step 5: Procedure to fire an event
    myevent();
}
}
}
Result :


0 comments:

Post a Comment