2017-05-28 15 views
1

我想創建一個標籤並將其顯示給用戶,但我不能。通過代碼創建並顯示標籤

我試圖將代碼複製中的InitializeComponent()的任何標籤...

(我使用工具箱中添加一個標籤到Form1。)

partial class Form1 
{ 
    private System.Windows.Forms.Label label1; 

    private void InitializeComponent() 
    { 
     this.label1.AutoSize = true; 
     this.label1.Location = new System.Drawing.Point(0, 0); 
     this.label1.Name = "label1"; 
     this.label1.Size = new System.Drawing.Size(35, 13); 
     this.label1.TabIndex = 0; 
     this.label1.Text = "label1"; 
    } 
} 

...和然後將其應用於我的標籤。

(我刪除我之前添加的標籤。)

public partial class Form1 : Form 
{ 
    private Label label; 

    public Form1() 
    { 
     InitializeComponent(); 

     label = new Label(); 

     label.AutoSize = true; 
     label.Location = new System.Drawing.Point(0, 0); 
     label.Name = "label"; 
     label.Size = new System.Drawing.Size(0, 0); 
     label.TabIndex = 0; 
     label.Text = "Test"; 

     //label.Enabled = true; 
     label.Visible = true; 
     //label.Select(); 
     //label.Show(); 
    } 
} 

但它不工作。 怎麼辦?

+3

你還沒有添加標籤的形式或其他家長,將允許它被顯示。 –

回答

2

你忘了重要的部分,即添加標籤到窗體的ControlCollection

this.Controls.Add(label); 
3

您需要添加標籤德將其添加到形式的管制清單。

因此,在你Form1()功能,添加follwoing創建標籤後:

this.Controls.Add(label);