访问按钮单击外部事件时创建的标签

时间:2015-09-05 23:09:33

标签: c# visual-studio

我是C#的新手和一般的编程。我试图使用Windows窗体应用程序和Visual Studio创建一个简单的购物清单应用。这就是我将项目添加到列表中的方式。

    public Form1()
    {
        InitializeComponent();
    }

    int x = 50;
    int y = 58;

    private void addButton_Click(object sender, EventArgs e)
    {
        Label itemName = new Label();
        itemName.Text = itemInput.Text;
        itemInput.Text = "";
        this.Controls.Add(itemName);
        itemName.Location = new Point(x, y);
        itemName.Width = 260;

        CheckBox coupon = new CheckBox();
        coupon.Location = new Point(x - 30, y);
        this.Controls.Add(coupon);

        y = y + 25;
    }

我遇到的主要问题是我无法更改标签的属性。 EX:

    public Form1()
    {
        InitializeComponent();
    }

    int x = 50;
    int y = 58;

    private void addButton_Click(object sender, EventArgs e)
    {
        Label itemName = new Label();
        itemName.Text = itemInput.Text;
        itemInput.Text = "";
        this.Controls.Add(itemName);
        itemName.Location = new Point(x, y);
        itemName.Width = 260;

        CheckBox coupon = new CheckBox();
        coupon.Location = new Point(x - 30, y);
        this.Controls.Add(coupon);

        Button deletButton = new Button();
        deletButton.Text = "delete";
        this.Controls.Add(deletButton);
        deletButton.Location = new Point(x + 260, y);
        deletButton.Width = 50;

        y = y + 25;
    }

    private void deletButton_Click(object sender, EventArgs e)
    {
        itemName.Text = "";
    }

它说

  

名称itemName在当前上下文中不存在

这是有道理的,因为它采用不同的方法。

我的主要问题是,我可以在该方法之外使itemName可用吗?或者我完全不知道这个问题并且必须重新设计这个程序吗?

1 个答案:

答案 0 :(得分:0)

假设你想要坚持动态添加控件,正如你现在所做的那样,那么一个简单的方法就是给它一个名字,然后用它来找到它:

// When you're creating it.
itemName.Name = "itemName";

// Finding it.
var itemName = (Label)this.Controls["itemName"];

// Another way to find it.
var itemName = (Label)this.Controls.Find("itemName", true);
相关问题