我正尝试在面板中添加一个控件(标签)。请参考代码:
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);
}
}
}
}
这是表格。我想要实现的是以编程方式生成3个不同的控件标签。但正如您所看到的,它只显示最后一个。关于这一点,请帮助我。我知道我的代码中有错误(因为它不工作).Thanks...
发布于 2010-08-02 10:22:57
将Label lbl = new Label();
放入循环中。
把偏移量变大,改变这个...
lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5))
...to:
lbl.Location = new System.Drawing.Point(52 + (x * 30), 58 + (x * 30))
发布于 2010-08-02 09:46:13
您需要在每次循环迭代中创建一个新标签。现在,您只创建了一个标签。
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);
}
}
发布于 2010-08-02 09:46:33
您需要将Label lbl = new Label();
放入您的for
循环中。
https://stackoverflow.com/questions/3384507
复制相似问题