i get an InvalidArgumentException while casting Control to System.Windows.Forms.Textbox:
Unable to cast object of type 'System.Windows.Forms.Control' to type 'System.Windows.Forms.TextBox'.
System.Windows.Forms.Control control = new System.Windows.Forms.Control();
control.Width = currentField.Width;
//here comes the error
((System.Windows.Forms.TextBox)control).Text = currentField.Name;
I am doing this, because I have different Controls (Textbox, MaskedTextbox, Datetimepicker...), which will dynamically be added to a panel and have the same basic properties (Size, Location... -> Control)
Why isn't the cast possible?
Joey is right:
your control isn't a textbox! You can test types using:
You control is an object of Control class which is parent class. May be more controls are inheriting from parent.
Hence a child can be cast as parent but not vice versa.
Instead use this
or
Make a TextBox object. That one will always be a TextBox and you do not need checking/casting for it.
All your controls inherit from System.Windows.Forms.Control. However, a TextBox is not the same as DateTimePicker, for example, so you cannot cast them to each other, only to the parent types. This makes sense as each control is specialized for doing certain tasks.
Given that you have controls of different types, you may wish to test the type first:
You can also speculatively cast to the type using the 'as' keyword:
The cast fails because
control
is not aTextBox
. You can treat aTextBox
as a control (higher up the type hierarchy) but not anyControl
as aTextBox
. For setting common properties you can just treat everything asControl
and set them whereas you have to create the actual controls you want to use beforehand: