Window casting out of control

I have this simple piece of code:

private void btnAdd_Click(object sender, EventArgs e) { if (AskForSaveBeforeClose(null)) { LoadForm<Soles>(btnAdd, "Add"); } } 

btnAdd now my only button with the type ToolStripDropDown . All other buttons are of type ToolStripButton . As you can see, I pass this button as an e parameter to the method, and I use ToolStripButton as the parameter type in many other methods. I don’t want to break my code too much, and I think it should be possible to btnAdd form ToolStripDropDownButton to ToolStripButton and solve my problem. This can be done, and if you have no other idea to save my code. I need a dropdown function, but at the moment any work is acceptable.

this is the 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 
+4
source share
2 answers

You cannot overlay ToolStripDropDownButton on ToolStripButton since the former does not inherit from the latter. However, both inherit from ToolStripItem , so you can use them instead.

Your opinion:

 var button = ((btnSoles as ToolStripItem) as ToolStripButton); 

However, this will not do what you want. Firstly, btnSoles always a ToolStripItem , so instead of using it directly, you should use:

 var item = (ToolStripItem)btnSoles; 

Then, if you really need the functionality provided by ToolStripButton and not ToolStripItem , then you should use as :

 var button = btnSoles as ToolStripButton; 

This will return null if btnSoles cannot be added to the ToolStripButton . If it is ToolStripDropDownButton , as you say, then it cannot be distinguished, and the result will be null . Please note that a double throw is not needed and is rarely required at all.

+2
source

You cannot use it if ToolStripDropDownButton does not get off ToolStripButton . If this is not the case, maybe they have a common ancestor that you can use as the type of your parameter.

+1
source

Source: https://habr.com/ru/post/1469547/


All Articles