ToolStripDropDownMenu and SourceControl ??

D

David

Hello all,

I have dynamic controls all associated with a single ContextMenuStrip. For
each menu item I have click event method. For each event I have cast sender
to ToolStripMenuItem to ContextMenuStip to use SourceControl to get the
control that initiated the event.

This all works well if the the menu items are one level deep on the
contextmenustrip control, but if I create a sub menu item doing the above
logic does not work.

First of all it gives a cast error of
"Unable to cast object of type "System...ToolStripDropDownMenu" to
"System...ContextMenuStrip." So in the case of a sub menu I changed the cast
to ToolStripDropDownMenu.

ToolStripMenuItem TlStrip = (ToolStripMenuItem)sender;
ToolStripDropDownMenu temp = (ToolStripDropDownMenu)TlStrip.Owner;
TlStrip = (ToolStripMenuItem)temp.OwnerItem;
ContextMenuStrip Mnu = (ContextMenuStrip)TlStrip.Owner;

Using above code Mnu.SourceControl is always null.

What am I doing wrong?
 
D

David

Its difficult to know when there are no responses wheather my question is not
detailed enough, not a common problem so no one is familiar with it to
answer, or just a dumb question (I have had a few). :)

For now going with need clarification. :)

I have a context menu strip as follows:
TestA
TestB - SubTestB

if I click on TestA Everything works fine. If I click on SubTestB the below
call to GetCtrl returns true but MyIcon is null.

Code Snippets:
///////////////////////////////////////////////////////////////
private bool GetCtrl(ToolStripMenuItem sender, ref MyDefIcon MyIcon)
{
bool bGood = false;
try
{
if (sender != null)
{
ContextMenuStrip Mnu = (ContextMenuStrip)sender.Owner;

if (Mnu != null)
{
MyIcon = (MyDefIcon)Mnu.SourceControl;
bGood = true;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

return (bGood);
}
///////////////////////////////////////////////////////////////
private void TestAToolStripMenuItem_Click(object sender, EventArgs e)
{
MyDefIcon MyIcon = null;
if(GetCtrl((ToolStripMenuItem)sender, ref MyIcon ))
{
if (MyIcon != null)
{
// do command
}
}
}
}
///////////////////////////////////////////////////////////////
private void SubTestBToolStripMenuItem_Click(object sender,
EventArgs e)
{
ToolStripMenuItem TlStrip = (ToolStripMenuItem)sender;
ToolStripDropDownMenu temp =
(ToolStripDropDownMenu)TlStrip.Owner;

MyDefIcon MyIcon = null;
if(GetCtrl((ToolStripMenuItem)temp.OwnerItem, ref MyIcon ))
{
if (MyIcon != null)
{
// do command
}
}
}
}




Please give advice or direction.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top