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.