尽管已定义,控件仍未出现

时间:2015-12-30 08:23:37

标签: c# winforms

我正在尝试以编程方式创建Windows窗体控件,而不使用WinForms Designer,但由于某些奇怪的原因,似乎没有任何控件被初始化。

当控件被拖入设计器时(很明显,当InitializeComponent()方法取消注释时),它们会出现,但是在外面以编程方式完成的任何操作都不会出现。

我已经完成了调试,代码运行没有任何错误,但标签没有出现。

问题:我错过了什么吗?

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

namespace WinForm_Console
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            // InitializeComponent();
            Initialize();
        }

        Label label1 = new Label();

        public void Initialize()
        {
            this.Text = "WinForm Console Application";
            SuspendLayout();
            label1.AutoSize = true;
            label1.Location = new System.Drawing.Point(129, 112);
            label1.Name = "label1";
            label1.Size = new System.Drawing.Size(35, 13);
            label1.TabIndex = 0;
            label1.Text = "label1";
            label1.Show();
            ResumeLayout(false);
            PerformLayout();
        }
    }
}

请注意,在我的原始尝试失败之后,这些代码中的一些是从设计器复制的(没有额外信息是相同的;初始标签,大小,逻辑挂起等)。

1 个答案:

答案 0 :(得分:2)

您必须将控件放在父控件Form中。创建标签后,执行此操作。

this.Controls.Add(label1);

像这样,

public void Initialize()
{
    this.Text = "WinForm Console Application";
    SuspendLayout();
    label1.AutoSize = true;
    label1.Location = new System.Drawing.Point(129, 112);
    label1.Name = "label1";
    label1.Size = new System.Drawing.Size(35, 13);
    label1.TabIndex = 0;
    label1.Text = "label1";
    label1.Show();
    this.Controls.Add(label1); //very very very important line!
    ResumeLayout(false);
    PerformLayout();
}
相关问题