铸造新System.Windows.Forms.Control的对象System.Windows.Forms.Textbox [英] casting new System.Windows.Forms.Control object to System.Windows.Forms.Textbox
问题描述
我得到一个InvalidArgumentException同时播送控制到System.Windows.Forms.Textbox:
无法投类型的对象'系统。 Windows.Forms.Control为键入'System.Windows.Forms.TextBox。
块引用>
System.Windows.Forms.Control的控制=新System.Windows.Forms.Control的();
control.Width = currentField.Width;
//这里来的错误
((System.Windows.Forms.TextBox)控制)。文本= currentField.Name;
我这样做,是因为我有不同的控件(文本框,MaskedTextBox中,dateTimePicker的...)这将被动态地添加到一个面板和具有相同的基本性质(大小,位置 - >控制)
为什么没有铸造可能
解决方案演员,因为
控制
的不是失败,一个文本框
的。你可以把一个文本框
作为对照(上涨类型层次结构),但没有任何控制
为文本框
。为了制定共同的属性,你可以只是把一切都为控制
,并设置它们,而你必须创建要事先用实际控制:文本框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 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: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;
这篇关于铸造新System.Windows.Forms.Control的对象System.Windows.Forms.Textbox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!