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…
     this.Save();
  }

Another solution which is slightly more complicated but more controlled.

DaTribe

http://images.experts-exchange.com/00186/content/flowplayer/flowplayer-3.1.4.min.js

1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:28:29:
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    }}

http://images.experts-exchange.com/00186/content/flowplayer/flowplayer-3.1.4.min.js

Leave a Reply