casting new System.Windows.Forms.Control object to System.Windows.Forms.Textbox

和自甴很熟 提交于 2019-12-22 01:26:11

问题


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?


回答1:


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;



回答2:


You control is an object of Control class which is parent class. May be more controls are inheriting from parent.

Hence a child can be cast as parent but not vice versa.

Instead use this

if (control is System.Windows.Forms.TextBox)
    (control as System.Windows.Forms.TextBox).Text = currentField.Name;

or

Make a TextBox object. That one will always be a TextBox and you do not need checking/casting for it.




回答3:


Joey is right:

your control isn't a textbox! You can test types using:

System.Windows.Forms.Control control = new System.Windows.Forms.Control();
control.Width = currentField.Width;

if (control is TextBox)
{
//here comes the error
((System.Windows.Forms.TextBox)control).Text = currentField.Name;
}



回答4:


All your controls inherit from System.Windows.Forms.Control. However, a TextBox is not the same as DateTimePicker, for example, so you cannot cast them to each other, only to the parent types. This makes sense as each control is specialized for doing certain tasks.

Given that you have controls of different types, you may wish to test the type first:

if(control is System.Windows.Forms.TextBox)
{
 ((System.Windows.Forms.TextBox)control).Text = currentField.Name;
}

You can also speculatively cast to the type using the 'as' keyword:

TextBox isThisReallyATextBox = control as TextBox;

if(isThisReallATextBox != null)
{
  //it is really a textbox!
}


来源:https://stackoverflow.com/questions/11223451/casting-new-system-windows-forms-control-object-to-system-windows-forms-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!