ASP.NET Basics: Delegates vs. Interfaces

The reason for using interfaces is that when exposing properties you want clients to only use what you allow them to, but save yourself the work of recreating a whole other control to do what NavigatorControl is already doing.

Notice now that the main page is not involved since all needed actions are happening on the two user controls.

using delegates

class NavigatorControl() : UserControl
    public event EventHandler SelectedItemChanged;

     //your navigation button handler
    protected void NextItemButton_OnClick(Object sender, EventArgs e)
      //Check for event registrations
      if(SelectedItemChanged != null)
        //passing a reference to the user control itself here with ‘this’
        //but it could be a reference to the actual item
        SelectedItemChanged(this, EventArgs.Empty);
// And then wireup that event in the parent user control:

public class ParentControl : UserControl
  protected void Page_Init(Object sender, EventArgs e)
    myNavControl.SelectedItemChanged += new EventHandler(myNavigatorControl_SelectedItemChanged);

  //the handler for the item changed event
  protected void myNavigatorControl_SelectedItemChanged(Object sender, EventArgs e)
     //and your parent level save…

Another solution which is slightly more complicated but more controlled.


public interface ISave{    void Save();}public class Navigator : System.Web.UI.UserControl, ISave{     public void Save()     {     }}// To make things really simple you could just// reference the control directly from the page// and call its save methodpublic class Profile: System.Web.UI.UserControl{    public ISave SaveControl    {        get { return ucNavigatorControl as ISave; }    }    public void ButtonClick(object sender, EventArgs e)    {        SaveControl.Save();        // Do something else    }}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.