2015-12-30 49 views
0

我試圖以編程方式創建Windows窗體控件,從頭開始不使用WinForms設計器,但出於某種奇怪的原因,沒有一個控件似乎被初始化。儘管被定義,控件仍未出現

當控件拖入設計器(顯然InitializeComponent()方法未註釋)時,會顯示它們,但不會出現編程外的任何操作。

我已經通過調試它,代碼運行沒有任何錯誤,但標籤沒有出現。

問題:我錯過了什麼嗎?


using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WinForm_Console 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      // InitializeComponent(); 
      Initialize(); 
     } 

     Label label1 = new Label(); 

     public void Initialize() 
     { 
      this.Text = "WinForm Console Application"; 
      SuspendLayout(); 
      label1.AutoSize = true; 
      label1.Location = new System.Drawing.Point(129, 112); 
      label1.Name = "label1"; 
      label1.Size = new System.Drawing.Size(35, 13); 
      label1.TabIndex = 0; 
      label1.Text = "label1"; 
      label1.Show(); 
      ResumeLayout(false); 
      PerformLayout(); 
     } 
    } 
} 

注意一些這個代碼是從設計師抄襲,此後我原來的嘗試失敗(這是沒有額外的信息,同樣的事情,最初的標籤,大小,邏輯懸浮等)

回答

2

您必須將控件放在父控件Form中。創建標籤後,執行此操作。

this.Controls.Add(label1); 

這樣,

public void Initialize() 
{ 
    this.Text = "WinForm Console Application"; 
    SuspendLayout(); 
    label1.AutoSize = true; 
    label1.Location = new System.Drawing.Point(129, 112); 
    label1.Name = "label1"; 
    label1.Size = new System.Drawing.Size(35, 13); 
    label1.TabIndex = 0; 
    label1.Text = "label1"; 
    label1.Show(); 
    this.Controls.Add(label1); //very very very important line! 
    ResumeLayout(false); 
    PerformLayout(); 
} 
+0

謝謝(這就是我失蹤了)。現在..等待14分鐘。 – aytimothy

相關問題