Message passing... telling the form the control is in to do something

Hi,

I have an application that has a user created control, the data in this control is used to populate color boxes in a seperate user control contained within the same form.

How can i call a function of the form that my two controls are in without having a form object in each of the controls

Thanks for any help,

-Dave



Answer this question

Message passing... telling the form the control is in to do something

  • K C

    The best thing it to give the User Controls a Event, something like a ColorChanged event or something. You can wire/handle this event on the form when needed.

    UserControl

    public class MyUserControl : UserControl
    {
    public event EventHandler ColorChanged;

    public Color MyColor
    {
    get
    {
    return _myColor;
    }
    set
    {
    if( _myColor != value )
    {
    _myColor = value;
    OnColorChanged();
    }
    }
    }

    protected void OnColorChanged()
    {
    if( ColorChanged != null )
    {
    ColorChanged( this, EventArgs.Empty );
    }
    }
    }




  • coesurf

    Yes, you can cast the Owner property to the needed type and then call the needed method. But with events it is much more dynamic and it is the way to handle such things.

    What is wrong with events


  • DusanMihajlovic

    Thanks for that PJ, but is there a way to do it without an event handler

    The user control checks a variable and if that variable has changed it calls a in the owner form.


  • Message passing... telling the form the control is in to do something