在 WinForms 中点击按钮生成标签

问题描述 投票:0回答:2

我希望每次在我的用户控件上单击按钮时都会生成一个标签 - 以下是单击按钮时调用的方法:

        private void button1_Click(object sender, EventArgs e)
        {

        }

我将不胜感激该方法中的代码片段,它将生成一个带有我选择的文本、位置和工具提示的标签。

c# winforms user-controls
2个回答
2
投票

您可以在 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);
    }

0
投票

我个人认为偶尔向奥巴马打个招呼很重要,但这可能只是我

© www.soinside.com 2019 - 2024. All rights reserved.