Changing a label's text in another form in C#?

I have a label called LabelX1. This is on form2. On form1, i have a button. I want the button's text to be transferred to the other form's label. I have tried

form2 frm2 = new form2();
frm2.labelX1.Text = this.button1.text;

But it does not work. Is there an easy, straight forward way of doing this?


Solution 1:

You need to expose your label or its property.

In form 2:

public string LabelText
{
    get
    {
        return this.labelX1.Text;
    }
    set
    {
        this.labelX1.Text = value;
    }
}

Then you can do:

form2 frm2 = new form2();
frm2.LabelText = this.button1.text;

Solution 2:

You could modify the constructor of Form2 like this:

public Form2(string labelText)
{
    InitializeComponent();
    this.labelX1.Text = labelText;
}

then create Form2 passing in the text:

Form2 frm2 = new Form2(this.button1.text);