And*_*ndy 0 c# controls textbox casting winforms
我将Control转换为System.Windows.Forms.Textbox时得到一个InvalidArgumentException:
无法将类型为"System.Windows.Forms.Control"的对象强制转换为"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;
Run Code Online (Sandbox Code Playgroud)
我这样做,因为我有不同的控件(Textbox,MaskedTextbox,Datetimepicker ...),它将动态添加到面板并具有相同的基本属性(大小,位置... - >控制)
为什么演员不可能?
演员失败,因为control 不是TextBox.您可以将a TextBox视为控件(在类型层次结构的较高位置),但不能将其Control视为a TextBox.要设置常用属性,您可以将所有内容视为Control并设置它们,而您必须事先创建要使用的实际控件:
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;
Run Code Online (Sandbox Code Playgroud)