2010-08-02 120 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

相关问题