2012-07-22 44 views
0

我是新來Visual C#和我目前堅持如何創建一個新的窗體(與代碼,而不是設計),並添加東西(即標籤和文本框)到這個新的窗體。這裏是我現在所擁有的:Visual C#:如何將控件添加到使用代碼創建的窗體?

namespace AccountInfo 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      profileForm profile = new profileForm(); // Make new form 
      profile.Name = "newProfile"; 
      profile.Text = "Add a new profile"; 
      profile.LabelText = "test"; 
      profile.Show();    // Display form 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 
    } 

    public class profileForm : Form 
    { 
     // Controls 
     Label label1 = new Label(); 

     public profileForm() 
     { 

     } 

     public string LabelText 
     { 
      set { label1.Text = value; } 
     } 

     private void profileForm_Load(object sender, EventArgs e) 
     { 

     } 
    } 
} 

當我運行此代碼時,我得到默認窗體,然後單擊button1。它帶來了一種新的形式,但沒有任何關係。我希望有一個標籤出現,但不會。我嘗試了多種不同的方式(這是我最近使用的方法),我無法得到任何東西顯示出來。我瀏覽過StackOverflow,還有一個話題出現了,但是它的解決方案對我來說並不適用。我會很感激任何洞察力:)謝謝!

編輯:我也嘗試過使用構造函數。它沒有幫助。

+0

右鍵點擊'的InitializeComponent();'和Goto定義(或F12)。你會看到表單設計器生成的代碼。 – 2012-07-22 07:17:46

回答

3

您正在內存中創建一個Label對象,但您並未將其分配給特定的父控件,或者將其設置爲位置等...... Google「動態創建控件C#」,您會發現一噸examples

你基本上需要從profileForm的某處調用以下兩行。

label1.Location = new Point(25,25); 

    this.Controls.Add(label1); 
+0

啊,謝謝。我錯過了Controls.Add行。我之前正在修補這個問題,但無法弄清楚它要我說什麼。我在這裏發佈的代碼有點少...比我之前搞亂的東西(所以如果它看起來像我沒有嘗試,情況並非如此:))。謝謝您的幫助! – MattM 2012-07-22 07:15:35

+0

不用擔心。不要忘記接受答案!乾杯。 – Dylan 2012-07-22 07:17:05

+0

哈哈,謝謝!新的StackOverflow以及...還沒有發現它的所有錯綜複雜:) – MattM 2012-07-22 07:27:33

1

正如迪倫所說,你需要將Label對象添加到profileForm負載情況如下:

this.Controls.Add(label1); 
+0

是否有任何理由堅持這個加載事件,而不是構造函數?似乎有幾種方法可以實現這個目標,但我不確定哪個是最好的,或者爲什麼... – MattM 2012-07-22 08:39:59

+0

沒有理由在Load事件中擁有它。你甚至可以在構造函數中添加控件。 – Shant 2012-07-22 08:45:29