Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Raising custom events from user controls - Part 106

Suggested Videos
Part 103 - Redirect http to https in iis using custom errors
Part 104 - Creating user controls
Part 105 - Using user controls on a webform

In this video we will discuss about 
1. Adding events to UserControls
2. Events and delegates



Most people feel "events and delegates" are complex and difficult to understand. Events and delegates are not that complex to understand, if the basics are right. To get the most out of this video, I strongly recommend to watch parts 36, 37 , 38 and 39 from C# Video series, and parts 104 and 105 from asp.net video series, before proceeding with this video.

Very important points to keep in mind, when understanding "Events and Delegates"
1. Delegates are function pointers, and their syntax is very similar to that of a function. 
2. Events are variables of type delegates with an event keyword.
If these points are not clear at the moment, don't worry, they will be much clear as we progress.



At the moment, the CalendarUserControl does not have any custom events. Let us say, we want to raise CalendarVisibilityChanged event every time the visibility of the calendar changes. The visibility of the calendar is toggled by clicking on the image button. 

The following are the steps to raise CalendarVisibilityChanged event from the CalendarUserControl
Step 1: Create CalendarVisibilityChangedEventArgs class that will contain the event data. 
public class CalendarVisibilityChangedEventArgs : EventArgs
{
    private bool _isCalendarVisible;

    // Constructor to initialize event data
    public CalendarVisibilityChangedEventArgs(bool isCalendarVisible)
    {
        this._isCalendarVisible = isCalendarVisible;
    }

    // Returns true if the calendar is visible otherwise false
    public bool IsCalendarVisible
    {
        get
        {
            return this._isCalendarVisible;
        }
    }
}

Step 2: Create CalendarVisibilityChangedEventHandler delegate. "sender" is the reference variable that points to the instance of the CalendarUserControl, that raises this event. "CalendarVisibilityChangedEventArgs" object will contain "CalendarVisibilityChanged" event data.
public delegate void CalendarVisibilityChangedEventHandler(object sender, CalendarVisibilityChangedEventArgs e);

Step 3: Create CalendarVisibilityChanged event. Remember that, an event is a variable of type delegate. In the line below, we are just creating a variable "CalendarVisibilityChanged" of type "CalendarVisibilityChangedEventHandler" with delegate keyword in front of it.
public event CalendarVisibilityChangedEventHandler CalendarVisibilityChanged;

Step 4: Create a protected virtual method to raise the event. Since this method is protected and virtual, all classes deriving from the CalendarUserControl class can overridde this method, if they wish to do so. This method enables the derived classes to do some additional work before the event can be raised. Just before raising the event, we are checking if CalendarVisibilityChanged is null. If you are not sure about this, please don't worry. This will be much clear in the next video session, when we discuss about consuming CalendarVisibilityChanged event.
protected virtual void OnCalendarVisibilityChanged(CalendarVisibilityChangedEventArgs e)
{
    if (CalendarVisibilityChanged != null)
    {
        CalendarVisibilityChanged(this, e);
    }
}

For example, if we have a class "DerivedCalendarUserControl" that derives from CalendarUserControl class. "DerivedCalendarUserControl" can override the virtual "OnCalendarVisibilityChanged()" method as shown below. "CalendarVisibilityChanged" will only be raised when "base.OnCalendarVisibilityChanged(e);" is invoked. So, using a "protected virtual" method to raise events is a very useful technique.
public class DerivedCalendarUserControl : CalendarUserControl
{
    // Other methods, properties etc..
    
    protected override void OnCalendarVisibilityChanged(CalendarVisibilityChangedEventArgs e)
    {
        // Do some additional work before raising the event
        base.OnCalendarVisibilityChanged(e);
    }
}

Step 5: Finally raise the event, whenever the visibility of the Calendar is changed in the CalendarUserControl. The calendar visibility is changed, whenevr the user clicks on the image button and when the date in the calendar is selected. So, raise "CalendarVisibilityChanged" event from ImgBtn_Click() and Calendar1_SelectionChanged(). Before raising the event, create and instance of "CalendarVisibilityChangedEventArgs" and pass event data, that is "true" or "false" to the contrustor of this class.
protected void ImgBtn_Click(object sender, ImageClickEventArgs e)
{
    if (Calendar1.Visible)
    {
        Calendar1.Visible = false;
        CalendarVisibilityChangedEventArgs calendarVisibilityChangedEventData = 
            new CalendarVisibilityChangedEventArgs(false);
        OnCalendarVisibilityChanged(calendarVisibilityChangedEventData);
    }
    else
    {
                
        Calendar1.Visible = true;
        CalendarVisibilityChangedEventArgs calendarVisibilityChangedEventData = 
            new CalendarVisibilityChangedEventArgs(true);
        OnCalendarVisibilityChanged(calendarVisibilityChangedEventData);
    }
}

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    txtDate.Text = Calendar1.SelectedDate.ToShortDateString();
    Calendar1.Visible = false;
    CalendarVisibilityChangedEventArgs calendarVisibilityChangedEventData = 
        new CalendarVisibilityChangedEventArgs(false);
    OnCalendarVisibilityChanged(calendarVisibilityChangedEventData);
}

Here is the complete CalendarUserControl code
public partial class CalendarUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Calendar1.Visible = false;
        }
    }

    protected void ImgBtn_Click(object sender, ImageClickEventArgs e)
    {
        if (Calendar1.Visible)
        {
            Calendar1.Visible = false;
            CalendarVisibilityChangedEventArgs calendarVisibilityChangedEventData = 
                new CalendarVisibilityChangedEventArgs(false);
            OnCalendarVisibilityChanged(calendarVisibilityChangedEventData);
        }
        else
        {
                
            Calendar1.Visible = true;
            CalendarVisibilityChangedEventArgs calendarVisibilityChangedEventData = 
                new CalendarVisibilityChangedEventArgs(true);
            OnCalendarVisibilityChanged(calendarVisibilityChangedEventData);
        }
    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        txtDate.Text = Calendar1.SelectedDate.ToShortDateString();
        Calendar1.Visible = false;
        CalendarVisibilityChangedEventArgs calendarVisibilityChangedEventData = 
            new CalendarVisibilityChangedEventArgs(false);
        OnCalendarVisibilityChanged(calendarVisibilityChangedEventData);
    }

    public string SelectedDate
    {
        get
        {
            return txtDate.Text;
        }
        set
        {
            txtDate.Text = value;
        }
    }
        
    public event CalendarVisibilityChangedEventHandler CalendarVisibilityChanged;

    protected virtual void OnCalendarVisibilityChanged(CalendarVisibilityChangedEventArgs e)
    {
        if (CalendarVisibilityChanged != null)
        {
            CalendarVisibilityChanged(this, e);
        }
    }
}

public class CalendarVisibilityChangedEventArgs : EventArgs
{
    private bool _isCalendarVisible;

    // Constructor to initialize event data
    public CalendarVisibilityChangedEventArgs(bool isCalendarVisible)
    {
        this._isCalendarVisible = isCalendarVisible;
    }

    // Returns true if the calendar is visible otherwise false
    public bool IsCalendarVisible
    {
        get
        {
            return this._isCalendarVisible;
        }
    }
}

public delegate void CalendarVisibilityChangedEventHandler(object sender, CalendarVisibilityChangedEventArgs e);

In the next video, we will discuss about consuming CalendarVisibilityChangedEvent.

1 comment:

  1. Thanks, had created my own user control, and was using an external button to remove controls from a control list.

    Using the Event for deleting controls works much better, Thanks for these videos, amazingly helpful

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.