2012-06-27 48 views
0

我得到一個InvalidArgumentException同時播送控制到System.Windows.Forms.Textbox:鑄造新System.Windows.Forms.Control的對象System.Windows.Forms.Textbox

無法投類型的對象「 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; 

我這樣做,因爲我有不同的控件(文本框,MaskedTextBox中,dateTimePicker的...),這將動態地添加到面板,並具有相同的基本屬性(大小,位置.. 。 - > Control)

爲什麼不能投射?

回答

5

演員失敗,因爲control不是TextBox。您可以將TextBox作爲控件(在類型層次結構中更高),但不能將Control作爲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; 
1

你控制是指類的對象是父類。可能更多的控件是從父類繼承的。

因此,孩子可以作爲父母而不是相反。

而是使用

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

做一個文本框對象。那將永遠是一個文本框,你不需要檢查/鑄造它。

1

喬伊是對的:

你的控制不是一個文本框!您可以使用以下方式測試類型:

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; 
} 
1

所有的控件都從System.Windows.Forms.Control繼承。但是,例如,TextBox與DateTimePicker不同,因此您不能將它們轉換爲彼此,而只能轉換爲父類型。這是有道理的,因爲每個控件都專門用於執行某些任務。

既然你有不同類型的控件,您不妨先測試類型:

TextBox isThisReallyATextBox = control as TextBox; 

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

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

使用「as」關鍵字您也可以推測強制轉換爲類型