1

I have an application that has 2 forms. When I click a button on form 2 I want it to be able to change the text in form1:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

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

The compiler throws an error

How do I do this?

0

2 Answers 2

8

You are confusing forms and form instances. A form is just a class. When Form1 displays, what's displaying is an instance of the Form1 class. When Form2 displays, an instance of Form2 is displaying.

You're trying to use

Form1.label1.Text = "Fred";

But you can only set a field or member of an instance. You're referring to the class "Form1".

You need two things. I'll assume that Form2 is launched from a button on Form1. Add a constructor to Form2 which accepts an instance of Form1:

private Form1 _starter;
public Form2(Form1 starter) : this()
{
    _starter = starter;
}

Then add a property to Form1 that exposes the label text: do not directly expose controls - only a given form should know what controls are on it:

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

Then have Form2 set that property:

private void button1_Click(object sender, EventArgs e)
{
    _starter.LabelText = "Fred";
}
Sign up to request clarification or add additional context in comments.

Comments

3

You probably launch an instance of Form2 from an instance of Form1, like this:

Form2 f2 = new Form2();
f2.Show();

If that's the case, you can then change text in the f2 instance of Form2 like this:

f2.label1.Text = "new text";

Note that you will need to make label1 a public field (not a good practice), or encapsulate it using a property. Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.