views:

2058

answers:

2

Hi, this is my problem:

I'm programmatically adding ToolStripButton items to a context menu.

That part is easy.

this.tsmiDelete.DropDownItems.Add("The text on the item.");

However, I also need to wire up the events so that when the user clicks the item something actually happens!

How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked.

+1  A: 

Couldn't you just subscribe to the Click event? Something like this:

ToolStripButton btn = new ToolStripButton("The text on the item.");
this.tsmiDelete.DropDownItems.Add(btn);
btn.Click += new EventHandler(OnBtnClicked);

And OnBtnClicked would be declared like this:

private void OnBtnClicked(object sender, EventArgs e)
{
    ToolStripButton btn = sender as ToolStripButton;

    // handle the button click
}

The sender should be the ToolStripButton, so you can cast it and do whatever you need to do with it.

Andy
Yes, that looks right. I knew this wasn't a difficult thing to do, but I just couldn't remember how to do it!
James
A: 

Thanks for your help with that Andy. My only problem now is that the AutoSize is not working on the ToolStripButtons that I'm adding! They're all too narrow.

It's rather odd because it was working earlier.


Update: There's definitely something wrong with AutoSize for programmatically created ToolStripButtons. However, I found a solution:

  1. Create the ToolStripButton.
  2. Create a label control and set the font properties to match your button.
  3. Set the text of the label to match your button.
  4. Set the label to AutoSize.
  5. Read the width of the label and use that to set the width of the ToolStripButton.

It's hacky, but it works.

James