Timothy
Timothy

Reputation: 383

Controls not appearing despite being defined

I'm trying to create a Windows Form Control programatically, from scratch without using the WinForms Designer, but for some odd reason, none of the controls seem to be initialized.

When controls are dragged into the designer (and obviously with the InitializeComponent() method uncommented), they appear, but anything done programically outside doesn't appear.

I've went through to debug it and the code runs without any errors, but the label doesn't appear.

Question: Am I missing something?


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();
        }
    }
}

Note that some of this code was copied from the designer, after my original attempt failed (which is the same thing without the extra information; initial label, size, logic suspending, etc.)

Upvotes: 0

Views: 55

Answers (1)

Ian
Ian

Reputation: 30823

You have to put the control in the parent control Form. After creating the label, do this.

this.Controls.Add(label1);

Like this,

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();
}

Upvotes: 2

Related Questions