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?
The cast fails because control
is not a TextBox
. You can treat a TextBox
as a control (higher up the type hierarchy) but not any Control
as a TextBox
. For setting common properties you can just treat everything as Control
and set them whereas you have to create the actual controls you want to use beforehand:
TextBox tb = new TextBox();
tb.Text = currentField.Name;
Control c = (Control)tb; // this works because every TextBox is also a Control
// but not every Control is a TextBox, especially not
// if you *explicitly* make it *not* a TextBox
c.Width = currentField.Width;
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
if (control is System.Windows.Forms.TextBox)
(control as System.Windows.Forms.TextBox).Text = currentField.Name;
or
Make a TextBox object. That one will always be a TextBox and you do not need checking/casting for it.
Joey is right:
your control isn't a textbox! You can test types using:
System.Windows.Forms.Control control = new System.Windows.Forms.Control();
control.Width = currentField.Width;
if (control is TextBox)
{
//here comes the error
((System.Windows.Forms.TextBox)control).Text = currentField.Name;
}
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:
if(control is System.Windows.Forms.TextBox)
{
((System.Windows.Forms.TextBox)control).Text = currentField.Name;
}
You can also speculatively cast to the type using the 'as' keyword:
TextBox isThisReallyATextBox = control as TextBox;
if(isThisReallATextBox != null)
{
//it is really a textbox!
}