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
controlis not aTextBox. You can treat aTextBoxas a control (higher up the type hierarchy) but not anyControlas aTextBox. For setting common properties you can just treat everything asControland set them whereas you have to create the actual controls you want to use beforehand: