I have a contextmenustrip in the toolStripDropDownButton with the following items and sub-items:
private void addItem()
{
toolStripDropDownButton1.DropDown = this.contextMenuStrip1;
contextMenuStrip1.Items.Add("item A");
contextMenuStrip1.Items.Add("item B");
contextMenuStrip1.Items.Add("item C");
addSubItem();
}
private void addSubItem()
{
for (int i = 0; i < contextMenuStrip1.Items.Count; i++)
{
(contextMenuStrip1.Items[i] as ToolStripMenuItem).DropDownItems.Add("SubItem 1");
(contextMenuStrip1.Items[i] as ToolStripMenuItem).DropDownItems.Add("SubItem 2");
(contextMenuStrip1.Items[i] as ToolStripMenuItem).DropDownItems.Add("SubItem 3");
}
}
I want to ask, how do I get text on items and sub-items if I just click on any sub-item. for example I click on Subitem 2 in item C, then the output is item C and Subitem 2
.
You can add the Click event for the sub items and use the OwnerItem property to get the parent menu for that sub item.
Inside the addSubItem()
foreach (ToolStripMenuItem item in (contextMenuStrip1.Items[i] as ToolStripMenuItem).DropDownItems)
{
item.Click += Item_Click;
}
and the Click event is
private void Item_Click(object sender, EventArgs e)
{
string parentMenuText = (sender as ToolStripMenuItem).OwnerItem.Text;
string subItemText = (sender as ToolStripMenuItem).Text;
}