Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i want to cast string to toolstripcombobox control

i have a string checked_module_name and this is a name of toolstripcombobox control
and i need to access this control by it's name but from the string
to modify it's selectedindex

ToolStripComboBox x = this.Controls[checked_module_name] as ToolStripComboBox;

give me an error Cannot convert type 'System.Windows.Forms.Control' to 'System.Windows.Forms.ToolStripComboBox' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
Posted
Comments
Sergey Alexandrovich Kryukov 21-Dec-15 12:38pm    
No, you don't want that. :-)
—SA

ToolStripComboBox is not a Control but is in fact a ToolStripItem and these cannot be put into a ControlCollection. A ToolStrip has an Items property of type ToolStripItemCollection. That's where you should look.

Alan.
 
Share this answer
 
It's not just impossible, it's not just makes no sense, it's totally wrong thinking.

I'm already with this kind of thinking. Some, getting the error or even exception "You cannot do A and B" try to ask "How to do A and B". The only right answer is: don't do it. How it cannot be unclear.

More to your case and possible practical needs: there are no cases when you need to find anything in System.Windows.Forms by name. All controls are accessed by reference. Even if you added a control in designer, the designer will generate a member for you which you can use to access a control instance. If you write code which creates a control instance yourself, you have to take care to preserve the reference to this control to be accessed in the point where you use it; it can be some variable or type member defined in the scope where you need to access the control.

How to create and use such variables or names? What is scope, how to control it? Answering such question would be nearly the same as asking "how to do programming?". From your question, I feel this is what you really need to learn. Don't worry, many did it; you will do, too.

[EDIT]

Don't be confused with the property Control.Name. In practice, the rule of thumb is: never rely on this property. It may or may not be assigned to some value, this value may or may not be unique (yes, if you simply add a control in a designer, if you try to modify it in the property grid of the designer, the unique value is chosen; it just does not guarantee anything). It would be the best just to ignore this property completely.

—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900