2014-09-30 55 views
0

如何將字符串轉換爲標籤。Publisher無法轉換爲字符串

string str = "Test String"; 
object objString = (object)str; 

Label lbl = (Label)objString; //InvalidCastException was unhandled 

lbl.BackColor = Color.Red; 
lbl.ForeColor = Color.Red; 
+0

奇怪的問題?聽起來像我如何從狗做貓... – Schwarzie2478 2014-09-30 08:36:15

回答

2

StringLabel ..(你不能轉換到StringLabel

試試這個:

string str = "Test String"; 

Label lbl = new Label() { Text = str }; 

lbl.BackColor = Color.Red; 
lbl.ForeColor = Color.Red; 
+0

Label lbl = this.Controls [「label」+ i] as Label; lbl.BackColor = Color.Red; lbl.ForeColor = Color.Yellow; 感謝您的幫助。如何在vb.net中編寫此代碼。 – Bullshit 2014-09-30 09:21:09

1

其實你可以將字符串轉換爲標籤,用一些小技巧

public class myLabel:Label 
{ 
    public static explicit operator myLabel(string text) 
    { 
    myLabel lbl = new myLabel(); 
    lbl.Text = text; 
    return lbl; 
    } 
} 

然後在你的演示文稿

myLabel lbl = new myLabel(); 
    lbl = (myLabel)"abc1234"; 
    form1.Controls.Add(lbl); 
+0

根據提出的問題,這個答案可能會導致更多的混淆...,不過它的好處是:-) – Schwarzie2478 2014-09-30 08:38:11

+0

很明顯,糖是糖,糖塊是糖塊,轉換並不意味着等於。它的意思是CONVERT – Behzad 2015-05-28 09:19:55