Tuesday, July 5, 2011

Events

In my last post I tried to show some example on Delegate. Here I will give another example of Events.
In windows form based application or in web based application we use events very commonly(button click, page load etc). It is something like a function or method is registered to that event and whenever the event is fired the registered method executed.
In .net Events and Delegates works hand-in-hand to provide a program's functionality. For any pre-defined dot net events or user defined custom events can be registered with any kind of method but this process is done by a delegate, which specifies the signature of the method that is registered for the event. Below is the code as an example of simple Events declaration.

 

namespace Event
{
//public delegate void MyDelegate();
public class EventProgram:Form
{
//public static event MyDelegate MyEvent;

public EventProgram()
{
Button clickMe = new Button();

clickMe.Parent = this;
clickMe.Text = "Click Here";
clickMe.Location = new Point(
(ClientSize.Width - clickMe.Width) / 2,
(ClientSize.Height - clickMe.Height) / 2);

clickMe.Click += new EventHandler(OnClickMeClicked);

// MyEvent += new MyDelegate(OnStartEvent);
// MyEvent();
}

public void OnClickMeClicked(object sender, EventArgs ea)
{
MessageBox.Show("My Button is Clicked.");
}

public void OnStartEvent()
{
MessageBox.Show("My Start Event Started :) ");
}
static void Main()
{
Application.Run(new EventProgram());
}
}
}

In the above example we are using a windows form containing a button only. Clicking on that button the registered method will be executed.

clickMe.Click += new EventHandler(OnClickMeClicked);

By this line we have assigned a delegate for the click event of the button. and the implementation of the delegate is as below :
public void OnClickMeClicked(object sender, EventArgs ea)
{
MessageBox.Show("My Button is Clicked.");
}

Look carefully that we didnot send the argument 'sender' and 'ea' but we put the method name.
Also in the same code I have added a custom event sample which is commented. Just unblock the lines of code and it will clear the understating how delegate is being used for method registering in events.

No comments:

Post a Comment

Rest Service using WEB API C#

This post will show a simple example of REST service built on Micrsoft WEB API framework. WEB API is an extensible framework from microsof...