铸造新System.Windows.Forms.Control的对象System.Windows.Forms.Textbox [英] casting new System.Windows.Forms.Control object to System.Windows.Forms.Textbox

查看:342
本文介绍了铸造新System.Windows.Forms.Control的对象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 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;

这篇关于铸造新System.Windows.Forms.Control的对象System.Windows.Forms.Textbox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆