Click here to Skip to main content
15,886,724 members

Response to: Call form method from user Control

Revision 2
It's not a good idea to try and call any methods in the form from the user control, it locks the control to a particular form, and means that it can't be re-used later, and the form can't be changed without considering the effects on the control.

Instead, create an event in the Control which the Form handles. The form then does what is necessary and feeds information back to the Control either via a public method or a property. In this case, create a HideRequest event that the form handles:
C#
/// <summary>
/// Event to indicate Control wishes to be hidden
/// </summary>
public event EventHandler HideRequest;
/// <summary>
/// Called to signal to subscribers that Control wishes to be hidden
/// </summary>
/// <param name="e"></param>
protected virtual void OnHideRequest(EventArgs e)
    {
    EventHandler eh = HideRequest;
    if (eh != null)
        {
        eh(this, e);
        }
    }
/// <summary>
/// Event to indicate Control wishes to be un-Hidden
/// </summary>
public event EventHandler ShowRequest;
/// <summary>
/// Called to signal to subscribers that Control wishes to be un-Hidden
/// </summary>
/// <param name="e"></param>
protected virtual void OnShowRequest(EventArgs e)
    {
    EventHandler eh = ShowRequest;
    if (eh != null)
        {
        eh(this, e);
        }
    }
All you need to do in the Control is call the OnHideRequest at the appropriate time, and the form can do the rest (or not, if it isn't interested in that feature)

[edit]Code block type changed from "xml" to "c#" - paste incorrectly identified the code - OriginalGriff[/edit]
Posted 25-Jan-13 8:05am by OriginalGriff.
Tags: ,