首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何以编程方式将控件添加到窗体?

如何以编程方式将控件添加到窗体?
EN

Stack Overflow用户
提问于 2010-08-02 09:40:09
回答 4查看 20K关注 0票数 3

我正尝试在面板中添加一个控件(标签)。请参考代码:

代码语言:javascript
复制
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...

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-08-02 10:22:57

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

把偏移量变大,改变这个...

代码语言:javascript
复制
 lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5))

...to:

代码语言:javascript
复制
lbl.Location = new System.Drawing.Point(52 + (x * 30), 58 + (x * 30))
票数 6
EN

Stack Overflow用户

发布于 2010-08-02 09:46:13

您需要在每次循环迭代中创建一个新标签。现在,您只创建了一个标签。

代码语言:javascript
复制
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);
    }
}
票数 2
EN

Stack Overflow用户

发布于 2010-08-02 09:46:33

您需要将Label lbl = new Label();放入您的for循环中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3384507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档