C# 以编程方式向 Panel 添加标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15385921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:37:02  来源:igfitidea点击:

Add label to Panel programmatically

c#panel

提问by Luci C

So I have a form, and I want to add some Panels with some controls(labels, and radiobuttons) when the form loads.
And I want to do it from the code, of course(it's for making an application with tests, and the questions will be random)
This is what I have done till now:

所以我有一个表单,我想在表单加载时添加一些带有一些控件(标签和单选按钮)的面板。
我当然想从代码中做到这一点(这是为了制作带有测试的应用程序,问题将是随机的)
这是我迄今为止所做的:

List<Panel>ls=new List<Panel>();

private void VizualizareTest_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 4; i++)
    {
        Panel pan = new Panel();
        pan.Name = "panel" + i;
        ls.Add(pan);
        Label l = new Label();
        l.Text = "l"+i;
        pan.Controls.Add(l);
        pan.Show();
    }

}

But it doesn't show anything on the form.

但它没有在表格上显示任何内容。

采纳答案by Steve

Add the panel just created to the Form.Controls collection

将刚刚创建的面板添加到 Form.Controls 集合中

private void VizualizareTest_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 4; i++)
    {
        Panel pan = new Panel();
        pan.Name = "panel" + i;
        ls.Add(pan);
        Label l = new Label();
        l.Text = "l"+i;
        pan.Location = new Point(10, i * 100);
        pan.Size = new Size(200, 90);  // just an example
        pan.Controls.Add(l);
        this.Controls.Add(pan);

    }
}