在WinForms中单击按钮时生成标签

afdcj2ne  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(113)

我希望每次单击UserControl上的按钮时都生成一个标签-下面是单击按钮时调用的方法:

private void button1_Click(object sender, EventArgs e)
        {

        }

如果方法内有一个代码片段,它将生成一个标签,其中包含我选择的文本、位置和工具提示,我将非常感激。

n1bvdmb6

n1bvdmb61#

您可以在windows窗体应用程序中轻松地完成此操作。以下代码片段只在特定位置生成一个label,带有硬编码文本和一些基本属性设置。您可以根据自己的要求修改它,例如,您可以相应地更改label name, location, text。希望这对您有所帮助。

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

或者也可以使用如下简化初始化;

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

相关问题