Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

oop - How to access one object from another form in C#?

Let's say I have "Form1" and "Form2", both are forms. In Form1 there are the Main Class and the Main method.

In Form1 I create an object like:

public myobject ob1 = new myobject();

But then, in Form2, I have this code:

 private void bdCancelar_Click(object sender, EventArgs e)
    {
        ob1.status = 1; // I can't access ob1 !!!
    }

Any help ?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need an instance of Form1. Normally if you have displayed this form you have instantiated it (Form1 form1 = new Form1()). Then you could operate on this instance and access public members:

form1.ob1.status = 1;

Another possibility is to have your Form2 constructor take a Form1 instance:

public class Form2: Form
{
    private readonly Form1 _form1;
    public Form2(Form1 form1)
    {
        _form1 = form1;
    }

    private void bdCancelar_Click(object sender, EventArgs e)
    {
        _form1.ob1.status = 1;
    }
}

and then when you are somewhere inside Form1 and want to create and show Form2:

var form2 = new Form2(this);
form2.ShowDialog();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...