问题
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)
{
ToolStripItem subItem = sender as ToolStripItem;
if (subItem == null) return;
ToolStripItem mainItem = subItem.OwnerItem as ToolStripItem;
if (mainItem == null) return;
ContextMenuStrip menuStrip = mainItem.Owner as ContextMenuStrip;
if (menuStrip == null) return;
DataGridView 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?
来源:https://stackoverflow.com/questions/30534417/source-control-is-null-when-accessing-from-a-sub-context-menu-item-in-c-sharp