-2

I would like a label to be generated every time a button is clicked on my UserControl - below is the method called whenever the button is clicked:

        private void button1_Click(object sender, EventArgs e)
        {

        }

I would be grateful for a code snippet inside the method that will generate a label with my choice of text, location and tooltip.

Alex B.
  • 2,145
  • 1
  • 16
  • 24
Gazdini9991
  • 49
  • 1
  • 2
  • 8

1 Answers1

2

You can do it easily in windows forms application. Following code snippet only generates a label at specific location with hardcoded text and some basic properties settings. You can modify it according to your requirement e.g. you can change label name, location, text accordingly. Hope this will be helpful for you.

private void button1_Click(object sender, EventArgs e)
        {
            var lblnew = new Label
            {
                Location = new Point(50, 50),
                Text = "My Label", //Text can be dynamically assigned e.g From some text box
                AutoSize = true,
                BackColor = Color.LightGray,
                Font = new Font("Microsoft JhengHei UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point, (byte)0)
            };
            //this refers to current form you can use your container according to requirement
            Controls.Add(lblnew);
        }

Or you can also use simplified initialization as follows;

private void button1_Click(object sender, EventArgs e)
    {
        var lblnew = new Label
        {
            Location = new Point(50, 50),
            Text = "My Label", //Text can be dynamically assigned e.g From some text box
            AutoSize = true,
            BackColor = Color.LightGray,
            Font = new Font("Microsoft JhengHei UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point, (byte)0)
        };
        //this refers to current form you can use your container according to requirement
        Controls.Add(lblnew);
    }
Ishtiaq
  • 238
  • 1
  • 2
  • 9
  • Thank you - is there anyway to make the label invisible and only have a tooltip which can be seen when hovered over? – Gazdini9991 Nov 21 '21 at 14:03
  • Yes you can do it by changing color and background of label. Can also hide this i.e. visible=false; You can also create tooltip for your control. For more information about creating tooltip do visit this [Link](https://stackoverflow.com/questions/9776077/how-can-i-add-a-hint-or-tooltip-to-a-label-in-c-sharp-winforms) – Ishtiaq Nov 21 '21 at 14:15
  • You are welcome. If it solves your problem then accept my [answer.](https://stackoverflow.com/help/someone-answers) – Ishtiaq Nov 21 '21 at 18:56