Copy this code as it is to the code part of your form.
Debug the code step by step to understand how events are called.
Delegates are used for calling events to implement event based system elegantly.
How to debug:
Click on the left side pane of your coding window to add a debug point.
press Ctrl+F11 to debug the code step wise.
CODE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace trialprograms3
{
public partial class Form1 : Form
{
//declaring the event handler delegate
delegate void ButtonEventHandler(object source,int clickCount);
class Button
{
//declaring the event
public event ButtonEventHandler ButtonClick;
//Function to trigger the event
public void clicked(int count)
{
MessageBox.Show("\nInside Clicked !!!");
//Invoking all the event handlers
if (ButtonClick != null)
ButtonClick(this,count); //the parameters sent to the event should match those of the above declared delegate
//delegate is like a function pointer
//onButtonAction event function is called from here.
}
}
public class Dialog
{
public Dialog()
{
Button b = new Button();
//Adding an event handler
b. ButtonClick += new ButtonEventHandler(onButtonAction);
//Triggering the event
b.clicked(1); //public void click is called here and a count of 1 is passes as parameter
b.ButtonClick += new ButtonEventHandler(onButtonAction);
b.clicked(1);
//Removing an event handler
b.ButtonClick -= new ButtonEventHandler(onButtonAction);
b.clicked(1);
b.ButtonClick -= new ButtonEventHandler(onButtonAction);
b.clicked(1);
}
//Event Handler function
public void onButtonAction(object source,int clickCount)
{
MessageBox.Show("Inside Event Handler !!!");
}
}
public Form1()
{
InitializeComponent();
new Dialog();
}
}
}
No comments:
Post a Comment