开发者

C# Using Multiple Forms

开发者 https://www.devze.com 2022-12-16 09:58 出处:网络
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:

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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号