Events in .NET Framework

Events are messages sent by objects to signals that certain action was performed as a result of a button click, text entry into the form and etc… There are two objects involve in the events. One is called Event sender which actually send an event which may be a button object and another is called Event receiver or object that receives and handles the event. Event sender does not know about receiver and as a result we need to have support function that will help delegate which event from Event sender object should be received by which Event receiver object.

.NET Framework uses pointer-like mechanism called Delegate. Delegate holds a reference to a method but unlike classes it can only hold references to methods that match its signature. One example is Delegate for handling web form button events. It’s called System.EventHandler and can only hold references to method with the following signature (Object sender, EventArgs e) where Object sender is type of object firing an event. You can derive a custom class from EventArgs if you need to pass additional information to the event handler of type void. Also, Delegate in this example can handle only method with the type “void”

protected void Page_Init(Object sender, EventArgs e)
{
        button1.Click += new EventHandler(ButtonClick);
}

protected void ButtonClick(Object sender, EventArgs e)
{
        message.Text = "Thanks for clicking!";
}