I'm trying to implement some code whereby I get the parent of the clicked toolstipmenuitem upto the root. If I query openly I eventually get a null exception from the one after the last parent, as you may expect where there is no parent to parent to get the parent of :
ToolStripMenuItem miOwnerItem = (ToolStripMenuItem)(mi.GetCurrentParent() as ToolStripDropDown).OwnerItem;
I've tried, unsuccessfully, below to implement a try catch and am wondering if anyone knows the best way to handle this null exception when querying for the OwnerItems.
private void MenuClick2(object sender, EventArgs e)
{
//Click event begins by setting up variables and bringing in the sender as a menu item
MenuResultsString.Visible = false;
MenuResultsString.Text = "";
ToolStripMenuItem mi = (ToolStripMenuItem)sender;
string WhatClicked = mi.ToString();
ToolStripMenuItem miOwnerItem = (ToolStripMenuItem)(mi.GetCurrentParent() as ToolStripDropDown).OwnerItem;
string WhatClicked1up = miOwnerItem.ToString();
string WhatClicked2up = "";
string WhatClicked3up = "";
string WhatClicked4up = "";
string WhatClicked5up = "";
float howDeep = 1;
try
{
ToolStripMenuItem miGrandpapaOwnerItem = (ToolStripMenuItem)(miOwnerItem.GetCurrentParent() as ToolStripDropDown).OwnerItem;
WhatClicked2up = miGrandpapaOwnerItem.ToString();
howDeep = 2;
try
{
ToolStripMenuItem miGreatGrandpapaOwnerItem = (ToolStripMenuItem)(miGrandpapaOwnerItem.GetCurrentParent() as ToolStripDropDown).OwnerItem;
WhatClicked3up = miGreatGrandpapaOwnerItem.ToString();
howDeep = 3;
CSMorWhut = IsThisTheSystemMenu(WhatClicked3up);
try
{
ToolStripMenuItem miGreatestGrandpapaOwnerItem = (ToolStripMenuItem)(miGreatGrandpapaOwnerItem.GetCurrentParent() as ToolStripDropDown).OwnerItem;
WhatClicked4up = miGreatestGrandpapaOwnerItem.ToString();
howDeep = 4;
try
{
ToolStripMenuItem miAncestralGrandpapaOwnerItem = (ToolStripMenuItem)(miGreatestGrandpapaOwnerItem.GetCurrentParent() as ToolStripDropDown).OwnerItem;
WhatClicked4up = miGreatestGrandpapaOwnerItem.ToString();
howDeep = 5;
}
catch (Exception f)
{
}
}
catch (Exception f)
{
}
}
catch (Exception f)
{
}
}
catch (Exception f)
{
}
}
Below is a copy of my exception:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Solution
StackTrace:
at Solution.App.MenuClick2(Object sender, EventArgs e) in E:\C02\Development\Visual Studio 2019\Source\Repos\Solution\App.cs:line 523
Any guidance would be greatly appreciated.