Search content within the blog

Tuesday, April 21, 2009

Delegates and Events in c# - Part IV

Events

Note : read the previous parts to understand this one thoroughly

Events are the messages sent by an object to indicate the occurrence of an event. Event can also be defined as a member that enables an object to provide notification. Events provide a very powerful means of inter-process communication. The most familiar example of events are graphical user interface, events are fired when any control is clicked on the GUI.
We can associate an event to a delegate.

Example...
Add a page called Events and Delegates.aspx in your code
Replicate your code- behind with the following

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Events_and_Delegates_EandD : System.Web.UI.Page
{
public delegate void PrintString(string msg);
public event PrintString eventprint;

protected void Page_Load(object sender, EventArgs e)
{
eventprint+=new PrintString(printmsg);
if (eventprint != null)
{
eventprint("Message using event and delgate"+"<br>");
}
}
}

public void printmsg(string msg)
{
Response.Write("Message:" + msg);
}

//output will be as follows
Message:Message using event and delgate

No comments:

Post a Comment