changing label text with button click

前提是你 提交于 2019-12-12 05:13:18

问题


I need to change the text of label on the button click, but it's not working and giving me run time error.I've got separate class for LABEL and separate for BUTTON.This is dummy code.the real code contains locations and sizes for both label and button.Everything is created dynamically. Thanks!

   /-------------------------------------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";
     }

回答1:


You can simply try it.

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



回答2:


You are trying to change the text of a null-referenced label:

// 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

In order for the code to work, you have to change the following:

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

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

Hope this helps!



来源:https://stackoverflow.com/questions/12335507/changing-label-text-with-button-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!