&引用;“全球”;Visual C#中的控件(不包含定义)?

&引用;“全球”;Visual C#中的控件(不包含定义)?,c#,button,controls,global,C#,Button,Controls,Global,我是一个初学者程序员,我想开发一个小游戏项目用于实践,因此我首先要做一些测试。 在这个测试中,我的程序以编程方式生成一个标签,我希望按钮按下时将其删除。问题是,它说myLabel没有定义,所以我想我应该让myLabel成为一个“全局”控件,但我不知道怎么做。有什么想法吗?谢谢你的帮助 以下是我目前的代码: namespace WindowsFormsApplication6 { public partial class Form1 : Form { publi

我是一个初学者程序员,我想开发一个小游戏项目用于实践,因此我首先要做一些测试。 在这个测试中,我的程序以编程方式生成一个标签,我希望按钮按下时将其删除。问题是,它说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);
    }