In C#, you have a Form that has a MenuStrip. The MenuStrip has several ToolStripMenuItem’s at different levels. The Form has a separate controller class. The controller class declares and initialises the Form and handles the Click events raised by the ToolStripMenuItem’s. With most other controls on a Form, a reference to the parent Form can be obtained by using the FindForm() method. The ToolStripMenuItem however, does not have this method. To obtain a reference to the Form, you have to recursively proceed up the tree of ToolStripMenuItem’s until you get to the MenuStrip control which does have the FindForm() method.
The following code can be pasted into the controller class and called in the ToolStripMenuItem’s event handler method:
public static Form GetOwnerForm(ToolStripItem theItem)
{
if (null != theItem.Owner)
{
if (null != theItem.Owner.FindForm())
{
return theItem.Owner.FindForm();
}
return Controller.GetOwnerForm(
((ToolStripDropDown)theItem.Owner).OwnerItem);
}
return null;
}
and called thus:
public void UserSearchView_menuitemEditUser_Click(object sender, EventArgs e)
{
Application.DoEvents();
ToolStripMenuItem theEditUserMenuItem =
sender as ToolStripMenuItem;
UserSearchView theParentView =
Controller.GetOwnerForm(theEditUserMenuItem)
as UserSearchView;
if (null != theParentView)
{
...
}
}
This method will save having to declare a global instance of the Form.
June 12th, 2007 