Visual C# 中的控件(不包含定义)"Global"?



我是一个初学者程序员,我想开发一个小的游戏项目进行练习,所以我先做一些测试。 在此测试中,我的程序以编程方式生成一个标签,我希望按钮在按下时将其删除。问题是,它说myLabel没有定义,所以我想我应该使myLabel成为"全局"控件,但我不知道如何操作。有什么想法吗?感谢您的帮助!

这是我到目前为止的代码:

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {  
        public Form1()
        {
            InitializeComponent();
            Label myLabel = new Label();
            this.Controls.Add(myLabel);
            myLabel.Location = new Point(50, 50);
            myLabel.Text = "Yay!";
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Controls.Remove(Label.myLabel);
        }
    }
}

使其成为类私有字段

public partial class Form1 : Form
{
    private  Label myLabel;
    public Form1()
    {
        InitializeComponent();
        myLabel = new Label();
        this.Controls.Add(myLabel);
        myLabel.Location = new Point(50, 50);
        myLabel.Text = "Yay!";
    }
    private void button1_Click(object sender, EventArgs e)
    {
       this.Controls.Remove(myLabel);
    }

最新更新