5

I am trying to change the color of a button when they click on a sub menu item (colors > red) from a Context Menu Strip.

This code is attached to user defined amount of buttons. To figure out which button they are trying to change, I am trying to go from the sub item to the source control like such: sender > owner tool strip > owner menu > source control.

My Code:

private void redToolStripMenuItem_Click(object sender, EventArgs e)
{
    var subItem = sender as ToolStripItem;
    if (subItem == null) 
        return;

    var mainItem = subItem.OwnerItem as ToolStripItem;
    if (mainItem == null) 
        return;

    var menuStrip = mainItem.Owner as ContextMenuStrip;
    if (menuStrip == null) 
        return;

    var dataGridView = menuStrip.SourceControl as DataGridView;
    if (dataGridView == null) 
        return; //null here

    MessageBox.Show(dataGridView.Name);
}

From what I've found on google, this appears to be a bug. Are there any workarounds for this?

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
  • 3
    Just use the ContextMenuStrip's Opening event. Store its SourceControl in a variable so you can use it later. – Hans Passant May 29 '15 at 17:29
  • This worked! Thanks! – AustinWBryan May 29 '15 at 18:58
  • Here's an example of just that http://stackoverflow.com/a/9739003/74585 – Matthew Lock Jan 11 '17 at 00:48
  • 2
    Hey, I came here for the same problem. When a normal (top-level) menu item in a context menu is clicked, its `Owner` is `ContextMenuStrip` and its `SourceControl` property has the ListView, but when a submenu (second-level) is clicked, the `Owner` is the parent menu (top-level), and even when I go up to the `ContextMenuStrip`, its `SourceControl` is null. – Damn Vegetables Feb 08 '17 at 17:18
  • @DamnVegetables Good job and what you proposed should be an answer and I'd love to upvote it if you turn it into an answer. – 8749236 Sep 04 '22 at 15:10

0 Answers0