How to get user control from contextMenu.SourceControl

I have a form populated with numerous controls of type ScreenDevice, a user control.  All instances of ScreenDevice are bound to a common contextMenu (contextMenu1), which contains a menuItem (menuItem3).  I have coded the click handler for this as follows:

        private void menuItem3_Click(object sender, System.EventArgs e)
{
ScreenDevicesd1;

sd1 = contextMenu1.SourceControl;      // *** Build error on this line ***
                sd1.UpdateDevice();
}

What I want to do is to determine which ScreenDevice raised the click event and then access it through a variable of the appropriate type.  But this code does not work - there is a build error:

"Cannot implicitly convert type 'System.Windows.Forms.Control' to 'Controls.ScreenDevice'".

How can do I do this conversion from contextMenu1.SourceControl to a variable of type ScreenDevice

Thanks,
-rick-


Answer this question

How to get user control from contextMenu.SourceControl

  • JeremyB

    The SourceControl property returns an object of type Control, from which your user control is derived.  In C#, you convert explicilty with a cast expression:
    sd1 = (ScreenDevice)contextMenu1.SourceControl;If the conversion fails (for instance, if the context menu was assigned to a non-ScreenDevice control), the previous line throws an InvalidCastException.  To avoid this, you can use the <i>as</i> keyword, which will make the conversion if possible or return null otherwise.
    sd1 = contextMenu1.SourceControl as ScreenDevice;
    if(sd1 != null)
    {
       // sd1 is safe to use
    }

  • How to get user control from contextMenu.SourceControl