Yami
Yami

Reputation: 1425

C# Get instance from a click event made by a contextmenu

I've got the following code (simplified):

private ContextMenuStrip createContextMenuStrip(Card card)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    cms.Items.Add("Send to the top of the deck", null, sendToDeck);
    return cms;
}

public void sendToDeck(object sender, EventArgs e)
{
    // **
}

The class Card has a member of the type PictureBox. On this PictureBox, the ContextMenu will be created. This works perfectly so far, BUT:

Here I want to access the instance the corresponding Card class which includes the clicked PictureBox's ContextMenu.

What possibilities do I have to achieve this?

Upvotes: 2

Views: 177

Answers (2)

Alessandro D'Andria
Alessandro D'Andria

Reputation: 8868

Control have a property Tag of type object where you can store data linked to the control. In your case you can strore the card:

private ContextMenuStrip createContextMenuStrip(Card card)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    var item = cms.Items.Add("Send to the top of the deck", null, sendToDeck);
    item.Tag = card; // so you have the card in your contextmenu
    return cms;
}

Then you can recovery in the event

public void sendToDeck(object sender, EventArgs e)
{
    var card = (Card)((Control)sender).Tag;
}

Upvotes: 2

Chris Sinclair
Chris Sinclair

Reputation: 23208

You can use a lambda expression which can refer to your card variable (see "Variable Scope in Lambda Expressions") and pass it to your method:

private ContextMenuStrip createContextMenuStrip(Card card)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    cms.Items.Add("Send to the top of the deck", 
                  null, 
                  (sender, e) => sendToDeck(sender, e, card));
    return cms;
}

public void sendToDeck(object sender, EventArgs e, Card card)
{
    // **
}

Assuming however that you don't care about feeding the object sender and EventArgs e in, it just becomes:

private ContextMenuStrip createContextMenuStrip(Card card)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    cms.Items.Add("Send to the top of the deck", 
                  null, 
                  (sender, e) => sendToDeck(card));
    return cms;
}

public void sendToDeck(Card card)
{
    // **
}

Upvotes: 4

Related Questions