Reputation: 9866
I have this simple piece of code:
private void btnAdd_Click(object sender, EventArgs e)
{
if (AskForSaveBeforeClose(null))
{
LoadForm<Soles>(btnAdd, "Add");
}
}
btnAdd
for now is my only button with ToolStripDropDown
type. All other buttons are of ToolStripButton
type. As you see I pass this button as e parameter to a method, and I use ToolStripButton
as a parameter type in a lot other methods. I don't want to break my code too much, and I think it should be possible to cast btnAdd
form ToolStripDropDownButton
to ToolStripButton
and solve my problem. Can this be done and if not do you have another idea to keep my code. I need the drop down functionality but any work-around is acceptable at the moment.
this is inheritance hierarchy :
System.Object System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ScrollableControl
System.Windows.Forms.ToolStrip
System.Windows.Forms.MenuStrip
System.Windows.Forms.StatusStrip
System.Windows.Forms.ToolStripDropDown
System.Windows.Forms.ToolStripDropDownMenu
System.Windows.Forms.ContextMenuStrip
Upvotes: 4
Views: 1964
Reputation: 50316
You cannot cast a ToolStripDropDownButton
to a ToolStripButton
as the former does not inherit from the latter. However, both inherit from ToolStripItem
so you can cast to that instead.
Your say you do:
var button = ((btnSoles as ToolStripItem) as ToolStripButton);
However, this is not going to do what you want. First, btnSoles
is always a ToolStripItem
so you should use a direct cast instead:
var item = (ToolStripItem)btnSoles;
Then, if you really need functionality that is provided by ToolStripButton
and not by ToolStripItem
, only then should you use as
:
var button = btnSoles as ToolStripButton;
This will return null
if btnSoles
cannot be cast to ToolStripButton
. If it is a ToolStripDropDownButton
, as you say, then it cannot be cast and the result will be null
. Note that the double cast is not necessary, and rarely needed in general.
Upvotes: 2
Reputation: 15893
You will not be able to cast it unless ToolStripDropDownButton
descends from ToolStripButton
. If it does not, may be they have common ancestor that you can use as your parameter type.
Upvotes: 1