1

I am on making a windows form and I have created label1 by drag and drop which is created within the partial class Form1. This obviously is visible on the screen.

I have made a new class called User and made a method that makes label2 by creating an instance and setting the border, text, location etc.

The problem is that label2 is not showing on the layout screen with label1.

I thought using Controls.Add(label2) would add it to the layout screen but doesn't. I have tried googling this but can't find the words to ask.

I have tried the below code:

using System;
enter code hereusing 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 WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        User user = new User();
        public Form1()
        {
            InitializeComponent();
            user.CreateLabel(this);
        }

    }
}

public class User
{
    public void CreateLabel(Form form)
    {
        Label label2 = new Label();
        label2.AutoSize = true;
        label2.Location = new System.Drawing.Point(0, 0);
        label2.Name = "label1";
        label2.Size = new System.Drawing.Size(35, 13);
        label2.TabIndex = 0;
        label2.Text = "label2";
        label2.Click += new EventHandler(label2_Click);
        form.Controls.Add(label2);
    }

    private void label2_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Dynamic button is clicked");
    }
}

From my limited knowledge of Windows Forms, I thought that using form.Controls.Add(label2) would add this to the design screen. It does add label2 when you run it but I want to see it in the layout screen.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • As you've discovered, this code affects the "run-time" version of the form, not the "design-time" layout view. It sounds like you may want to do code generation, where you are programmatically adding a label to the form code. Maybe this will point you in the right direction? https://learn.microsoft.com/en-us/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2019 – jefftrotman Aug 03 '19 at 14:07
  • Hi jefftrotman, what do you mean by code generation? I am trying to create all User events within a User class, all Unit events within a Unit class, all SigGen events within a SigGen class... you get the picture. I could do all this within Form1 class but I wanted to try out OOP. How would this usually be done please? – Cornelius Flint the III Aug 03 '19 at 14:31

0 Answers0