Simple custom Event & Delegates demonstration.

Puneet20884
Posted by in C# category on for Beginner level | Views : 5117 red flag

Hi,
The article will help you to fire your events (custom events) from the control's events of a Web User Control from the Web Page.
Not going into Much of the theories,I am mentioning the code below to be used for User Control and Web Page.

In my case here i want to fire a Button's Click event from my web page.
You can in mean way can achieve any event like Drop down's SelectedIndexChanged, Data Grid's Paging , Sorting, Command event or any one of any control by just changing the parameter types of the arguments in the Delegate that you are creating the object of.

Here the Code goes of User Control:

public partial class WebUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public delegate void MyDel(object sender, EventArgs e);
    //The argument's types above will be as of the event you want to call your manual event in.

    public event MyDel evn; // Event of the above delegate
    protected void Button1_Click(object sender, EventArgs e)
    {
        evn(sender, e);
        //Call this manual event inside the event you want to handle from the Web Page.
    }
}

Here the Code goes of Web Page:

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebUserControl1.evn += new WebUserControl.MyDel(WebUserControl1_evn);
        // Define the function pointer in which you will create the custom rules or business rule as per requirement
        //So when ever the event of the button in the user control will fire, this event handler will be called
    }

    void WebUserControl1_evn(object sender, EventArgs e)
    {
        if(Request["a"] == null) //Condition 1
        {
            Response.Write("asdfasdf");
        }
        else
        {
            Response.Write("asdfasdfadfasdfasdf");
        }
    }
}

I wish this will give you a good idea and will solve the problems of many people of controling the events of Web User Control's Controls from the page.

Also please try for other events of other controls and let me know your feedback.
Page copy protected against web site content infringement by Copyscape

About the Author

Puneet20884
Full Name: Puneet Sharma
Member Level: Bronze
Member Status: Member
Member Since: 12/8/2009 3:55:51 AM
Country: India
Best Regards, Puneet Sharma - Infosys Pune, India
http://www.sumitgarg.net/post/2010/04/07/Image-Resigning-in-ASP-Dot-with-C-using-httphandler.aspx
Working as Tech Analyst for TCS - London (UK)

Login to vote for this post.

Comments or Responses

Posted by: Abhi2434 on: 1/15/2010
It is almost the same one that I posted in my blog few days back:

http://dotnetricks.blogspot.com/2010/01/how-to-expose-events-from-usercontrol.html

Cheers.

Login to post response

Comment using Facebook(Author doesn't get notification)