用按钮单击更改标签文本

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

我需要更改按钮单击时标签的文本,但它不起作用并给我运行时错误。我有LABEL的单独类和BUTTON分开。这是虚拟代码。真实代码包含位置和大小标签和按钮。一切都是动态创建的。谢谢!

   /-------------------------------------LABEL class-------------------------------/
   private Label label1;

   public Label getLabel1()
   {
       return label1;
   }

   public LABEL()
   {
       label1 = new Label();
   }

    public void print()
    {            
        label1.Text = "x";
        Controls.Add(label1);
    }//

  /-------------------------------------BUTTON class----------------------------------/
    private Button button1;

    public BUTTON()
    {

    }

    public void print()
    {
        button1 = new Button();
        button1.Click +=new EventHandler(button1_Click);
        Controls.Add(button1);
    }

     public void button1_Click(object sender, EventArgs e)
     {
        LABEL label = new LABEL();
        label.getLabel1().Text = "y";
     }
c# button label
2个回答
1
投票

你可以试试吧。

private void button1_Click(object sender, EventArgs e){label1.Text = "Hi";label1.Refresh();}

0
投票

您正在尝试更改空引用标签的文本:

// Label Class
private Label label1;
public Label getLabel1()
{
    return label1;
}
// Button Class
LABEL label1 = new LABEL();
label1.getLabel1().Text = "y";
// getLabel1 is returning null, because you have not initialized label1

为了使代码有效,您必须更改以下内容:

public LABEL()
{
    label1 = new Label();
}

public void print()
{
    label1.Text = "x";
    Controls.Add(label1);
}

希望这可以帮助!

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