更新时间:2023-12-06 15:01:10
演员,因为控制
的不是失败,一个文本框
的。你可以把一个文本框
作为对照(上涨类型层次结构),但没有任何控制
为文本框
。为了制定共同的属性,你可以只是把一切都为控制
,并设置它们,而你必须创建要事先用实际控制:
文本框TB =新的TextBox();
tb.Text = currentField.Name;
控制C =(控制)TB; //这个工程,因为每一个文本框也是控制
//但并不是每个控制是一个文本框,尤其不要
//如果你显式的指定使它*不*一个文本框
C .WIDTH = currentField.Width;
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;