Monday, April 11, 2011

Event Handling With Dynamic ToolStripItem

Hello,

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.

From stackoverflow
  • 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...
    }
    
    Matías : thanks! that is what i was looking for

0 comments:

Post a Comment