Tute
Tute

Reputation: 7013

Event Handling With Dynamic ToolStripItem

I'm trying to dynamically add items to a toolstrip with the following code:

contextMenuStrip.Items.Add(string.Format("{0} kB/s", currSpeed), null, new EventHandler(Connection.SetSpeed));

The problem is that I need to pass a parameter to Connection.SetSpeed: currSpeed (int). How can I do that?

Thanks for your time. Best regards.

Upvotes: 1

Views: 457

Answers (1)

Kieron
Kieron

Reputation: 27127

Calling add will return you a ToolStripItem, if you set it's Tag property to the currSpeed variable you should be able to pull that ToolStripItem out via the sender argument in the Connection.SetSpeed method when the item gets clicked...

ToolStripItem item = contextMenuStrip.Items.Add(string.Format("{0} kB/s", currSpeed), null, new EventHandler(Connection.SetSpeed));
item.Tag = currSpeed;

void Connection.SetSpeed (object sender, EventArgs e)
{
    ToolStripItem item = (ToolStripItem)sender;
    int currSpeed = (int)item.Tag;

    // Do stuff...
}

Upvotes: 1

Related Questions