Blog Archives

C# Event Handlers and Delegates in ASP .Net with Web User Controls

This article should help as a general how to on event handlers and delegates in C# as well as propose a different way to handle cross page methods in your ASP .Net website from a web user control or other page.

Dilemma:
Page contains user control which has some methods and functionality built in. When a particular button click or other generic event is fired in the user control, it needs to call back to the parent page.

Solution:
Create event handlers and their delegates in the user control, fire them from the methods tied to the internal controls protected events, and define the methods that will handle the new events in the page (see code below).

C# (with some VB notes):

//delegate declaration not necessary in VB
 public delegate void MyCustomHandler(object sender, EventArgs e);
    public event MyCustomHandler SomethingClicked;

    protected void btnButton1_Click(object sender, EventArgs e)
    {
//tell our parent page which is listening for the event that something was clicked
//this null check and method invoke is the equivalent of raise event in VB
        if (SomethingClicked != null)
        {
            SomethingClicked(sender, e);
        }

//do some other work specific to this button in the user control
    }


That’s the code for your user control, now for the page.

 protected void Page_Load(object sender, EventArgs e)
    {

        MyUserControl1.SomethingClicked += new MyUserControl1.MyCustomHandler(MyUserControl1_SomethingClicked);
        

        if (!Page.IsPostBack)
        {
            //do my other normal work
        }

    }

    protected void MyUserControl1_SomethingClicked(object sender, EventArgs e)
    {
//voila! clicking on the button in your user control will fire this method on the parent page!
    }

Alternatively instead of declaring your own delegate, you can also simply use:

//in control
public event EventHandler SomethingClicked;

//and in page load
MyUserControl1.SomethingClicked+= new EventHandler(MyUserControl1_SomethingClicked);

If you have no need for custom arguments, this a good quick alternative that may be well liked by VB users where delegate declaration is optional.

References
DeveloperFusion, http://www.developerfusion.com/article/2137/event-handling-in-net-using-c/3/
VBForums, http://www.vbforums.com/showthread.php?t=521089
MSDN (events and delegates), http://msdn.microsoft.com/en-us/library/17sde2xt%28v=vs.71%29.aspx
MSDN (dynamically bind event handlers), http://msdn.microsoft.com/en-us/library/t3d01ft1%28v=vs.80%29.aspx
MSDN (which control raised an event), http://msdn.microsoft.com/en-us/library/zk6b17bs%28v=vs.80%29.aspx
ASP.Net (blog), http://weblogs.asp.net/rweigelt/archive/2005/01/14/353333.aspx
TechRepublic, http://www.techrepublic.com/article/simplify-net-class-communication-with-delegates/1050214
Akadia, http://www.akadia.com/services/dotnet_delegates_and_events.html

Advertisements

call parent page from user control to invoke page methods

To illustrate how we will accomplish this using Reflections, we will be using repeater in a user control within a page.

Your repeater loads data easily within the user control code behind, but you want to utilize the “ItemCommand” event of the repeater to update some values on the page page.

Here’s how this can work:

Parent Page:

//the name doesn't have to match the corresponding method on user control but makes code more readable
    public void rptRepeaterName_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {

        try
        {
            if (e.CommandName == "commandname")
            {
               //do some work on data then call update on parent page to reload data and show within a modal

                ParentPage_UpdatePanel.Update();
                ParentPage_ModalPopup.Show();

            }
        }
        catch (Exception ex)
        { 
//do something
            throw new ApplicationException(ex.ToString());
        }

    }

User Control:

    protected void rptRepeaterName_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        MethodInfo mi = this.Page.GetType().GetMethod("rptRepeaterName_ItemCommand", BindingFlags.Public | BindingFlags.Instance);

//note we specify parent page as the object and pass in a new object representing our repeater and carrying its parameters
        if (mi!=null) mi.Invoke(this.Page, new Object[] {sender,e });

    }

Voila! Behold the power of Reflections! 8)

In particular, one of the references below (thanks Bruce Barker!) helped me come to this answer, however, the exact code he presents will result in a “Non-static method requires a target” error.

To avoid this error, make sure you always pass in the object when invoking a method that is non-static (within a class that is instantiated).

To learn more about reflections and how it works search my blog for other examples, and visit MSDN for a good overview.

References
Velocity Reviews, http://www.velocityreviews.com/forums/t71075-invoke-methods-on-the-parent-page-from-the-user-control.html
Reflection Overview (MSDN), http://msdn.microsoft.com/en-us/library/f7ykdhsy%28v=vs.71%29.aspx