views:

770

answers:

2

C#: How to detect who is the caller of a context menu's menu item when linked to two different objects?

I have two labels, lblOn and lblOff. I am linking 'one' contextmenu to both labels to discard having to make two of the same.

How would I go upon finding out which label object called the contextmenu.menuitem? That way the clicked on menuitem knows if it was it it's contextmenu was called by the lblOn label or lblOffline?

+8  A: 

Check the SourceControl property of the ContextMenuStrip.

SLaks
+3  A: 

Disregard. After googling a bit more, I found a solution + code example.

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
    //Make sure the sender is a ToolStripMenuItem
    ToolStripMenuItem myItem = sender as ToolStripMenuItem;
    if (myItem != null)
    {
        //Get the ContextMenuString (owner of the ToolsStripMenuItem)
        ContextMenuStrip theStrip = myItem.Owner as ContextMenuStrip;
        if (theStrip != null)
        {
            //The SourceControl is the control that opened the contextmenustrip.
            //In my case it could be a linkLabel
            LinkLabel linkLabel = theStrip.SourceControl as LinkLabel;
            if (linkLabel == null)
                MessageBox.Show("Invalid item selected.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                if (MessageBox.Show(string.Format("Are you sure you want to remove BOL {0} from this Job?", linkLabel.Text), "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    linkLabel.Text = Program.NullValue(linkLabel);
                }
            }
        }
    }
}

Source: http://www.tek-tips.com/viewthread.cfm?qid=1441041&page=8