tags:

views:

48

answers:

1

In my last post I have asked feedback of my code.Today I have also crated a simple dummy project.If you think that now I have basic knowledge of delegates and events, then please tell me some difficult task for delegates and events. Below is my code-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DelegatesAndEvents.aspx.cs" Inherits="WebProjects.DelegatesAndEvents" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btn1" runat="server" onclick="btn1_Click" Text="ONE" /><br />
        <asp:Button ID="btn2" runat="server" onclick="btn2_Click" Text="TWO" /><br />
        <asp:Button ID="btn3" runat="server" onclick="btn3_Click" Text="THREE" /><br />

        <asp:Label ID="lblText" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>


using System;

namespace WebProjects
{
    public partial class DelegatesAndEvents : System.Web.UI.Page
    {
        public delegate void MyDelegate(string val);

        public event MyDelegate myEvent;
        protected void Page_Load(object sender, EventArgs e)
        {
            myEvent += SetLabelValue;
        }

        public void SetLabelValue(string val)
        {
            lblText.Text = val;
        }

        protected void btn1_Click(object sender, EventArgs e)
        {
            if(myEvent!=null)
            {
                string value = "button one is clicked.";
                myEvent(value);
            }
        }

        protected void btn2_Click(object sender, EventArgs e)
        {
            if (myEvent != null)
            {
                string value = "button two is clicked.";
                myEvent(value);
            }
        }

        protected void btn3_Click(object sender, EventArgs e)
        {
            if (myEvent != null)
            {
                string value = "button three is clicked.";
                myEvent(value);
            }
        }
    }
}

Thanks in advance.

+1  A: 

My first advice is that don't write these self-study programs under an asp.net project, because you must understand the life-cycle of asp.net pages first. A console application is easier to write and test.

And in your question, the code seems to be correct. It will be better if you give significant names to the variables, which can also help you understand delegates and events better.

Your code is improvable, by integrating 3 click events into one. Actually in the code, myEvent is used like an ordinary delegate, no necessary to be an event. This answer may helpful to understand differences between delegate/event better.

Danny Chen
Thanks Danny...
Mohit Kumar