Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

winforms

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?

like image 396
Hunter Mitchell Avatar asked May 22 '12 14:05

Hunter Mitchell


People also ask

How do I change the name of a label in Windows Forms?

Windows. Forms namespace. Add a Label control to the form - Click Label in the Toolbox and drag it over the forms Designer and drop it in the desired location. If you want to change the display text of the Label, you have to set a new text to the Text property of Label.


2 Answers

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;
like image 108
Davio Avatar answered Oct 11 '22 04:10

Davio


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);
like image 9
Eric Dahlvang Avatar answered Oct 11 '22 02:10

Eric Dahlvang