2010-08-02 122 views
2

我試圖在面板中添加一個控件(標籤)。 請參閱代碼:如何以編程方式將控件添加到窗體?

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

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

     private void button1_Click(object sender, EventArgs e) 
     { 
      Label lbl = new Label(); 

      for (int x = 0; x <= 3; x++) 
      { 
       //create new label location after each loop 
       //by multiplying the new value of variable x by 5, so the new label 
       //control will not overlap each other. 
       lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5)); 
       //create new id and text of the label 
       lbl.Name = "label_" + x.ToString(); 
       lbl.Text = "Label " + x.ToString(); 

       this.panel1.Controls.Add(lbl); 
      } 
     } 
    } 
} 

screenshot

這裏的形式。我試圖完成的是以編程方式生成3個不同的控制標籤。但正如你所看到的,它只顯示最後一個。請幫助我解決這個問題。我知道我的代碼有問題(因爲它不工作)。謝謝...

+0

對不起,我不知道如何接受answers..just在新手這個論壇。如何做到這一點? – yonan2236 2010-08-02 02:08:10

+0

當你問一個問題時,在向上/向下投票下面有一個複選標記。要接受正確答案,請點擊複選標記。它給予用戶額外的點數,並讓其他人知道哪些答案有效,如果他們有類似的問題。 – 2010-08-02 02:18:10

+0

謝謝先生... – yonan2236 2010-08-02 02:20:28

回答

5

Label lbl = new Label();放入循環中。

,使偏移較大,改變了...

lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5)) 

...到:

lbl.Location = new System.Drawing.Point(52 + (x * 30), 58 + (x * 30)) 
+0

現在它的工作:) 謝謝你先生... – yonan2236 2010-08-02 02:33:15

+0

非常歡迎:-) – 2010-08-02 02:35:40

2

您需要在每次循環迭代中創建一個新標籤。現在你只能創建一個標籤。

private void button1_Click(object sender, EventArgs e) 
{ 
    for (int x = 0; x <= 3; x++) 
    { 
     Label lbl = new Label(); 

     //create new label location after each loop 
     //by multiplying the new value of variable x by 5, so the new label 
     //control will not overlap each other. 
     lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5)); 
     //create new id and text of the label 
     lbl.Name = "label_" + x.ToString(); 
     lbl.Text = "Label " + x.ToString(); 

     this.panel1.Controls.Add(lbl); 
    } 
} 
+0

我只是做了你所說的,但根本沒有任何變化...... – yonan2236 2010-08-02 02:15:00

+0

這不是工作先生.. – yonan2236 2010-08-02 02:15:59

+0

嗯,看看它的代碼看起來應該創建4個標籤。 ('x <= 3')。 – 2010-08-02 02:19:26

0

你需要把你的Label lbl = new Label();循環for裏面。

+0

好的,謝謝...... :) – yonan2236 2010-08-02 02:09:18

+0

我只是做了你所說的,但沒有任何變化...... – yonan2236 2010-08-02 02:12:59

+0

它的工作......謝謝先生 – yonan2236 2010-08-02 02:42:54

相關問題