问题
so I have a problem with dynamically adding items to menuStrip. I mean I know how to add items to it, but I dont have any idea how to make Click handler to those dynamically added items.
for(int i = 0; i < grupiuKiekis; i++)
{
row2 = mysql_fetch_row(result2);
System::String^ grupesName = gcnew String(row2[1]);
pasirinktiGrupęToolStripMenuItem->DropDownItems->Add(grupesName);
}
Please show me the right way to do it.
回答1:
The Add method has several overloads. You could use the overload that allows you to specify an EventHandler explicitly, or you could construct a ToolStripItem, set up a click handler on that, and then add the ToolStripItem.
Edit
Here's basically what you want to do:
for(int i = 0; i < grupiuKiekis; i++)
{
row2 = mysql_fetch_row(result2);
System::String^ grupesName = gcnew String(row2[1]);
ToolStripItem^ item = gcnew ToolStripItem();
item->Text = grupesName;
item->Click += gcnew EventHandler(this, &Form1::clickHander);
pasirinktiGrupęToolStripMenuItem->DropDownItems->Add(item);
}
void clickHander(Object^ sender, EventArgs^ e)
{
ToolStripItem^ item = (ToolStripItem^) sender;
System::String^ grupesName = item->Text;
// Do what you need to do.
}
来源:https://stackoverflow.com/questions/10033232/dynamically-adding-menustrip-items