Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public partial class _Default : System.Web.UI.Page
    {
        public delegate void mydelegate();
        public event mydelegate myevent;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            myevent += new mydelegate(method1);
            myevent += new mydelegate(method2);
            myevent += new mydelegate(method3);
            myevent += new mydelegate(method4);
        }

        public void method1()
        {

            Response.Write("Method1");
            throw new Exception();

        }
        public void method2()
        {

            Response.Write("Method2");

        }
        public void method3()
        {

            Response.Write("Method3");

        }
        public void method4()
        {

            Response.Write("Method4");

        }

my above code is not working i.e. on button click method1,2,3,4 are not getting called.
Thanks in Advance.
Posted

1 solution

Well no - they won't. You aren't calling them at all - you are just adding them to the list of methods to call when you do action the delegate. In fact, each time you press the button, you add four more methods to the list, so if you did call the delegate itself, after the first press it would call each one once, after the second press it would call each one twice, and so on.

Try this:
C#
protected void Page_Load(object sender, EventArgs e)
{
    myevent += new mydelegate(method1);
    myevent += new mydelegate(method2);
    myevent += new mydelegate(method3);
    myevent += new mydelegate(method4);
}
protected void Button1_Click(object sender, EventArgs e)
{

    if (myevent != null)
    {
        myevent();
    }
}
 
Share this answer
 
Comments
CPallini 28-May-14 16:44pm    
5.
Rakesh Agarwal1984 31-May-14 14:55pm    
Suppose if myevent is null,then what need to be done to call the myevent i.e. now to make myevent not null

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900