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?
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
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:
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:
Then have Form2 set that property: