Source control is null when accessing from a sub context menu item in C#

本秂侑毒 提交于 2019-12-10 15:48:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!