如何在C#中从另一个表单访问一个对象?(How to access one object from another form in C#?)

编程入门 行业动态 更新时间:2024-10-11 13:27:13
如何在C#中从另一个表单访问一个对象?(How to access one object from another form in C#?)

假设我有“Form1”和“Form2”,两者都是表格。 在Form1中有Main Class和Main方法。

在Form1中,我创建了一个对象,如:

public myobject ob1 = new myobject();

但是,在Form2中,我有这个代码:

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

有帮助吗?

谢谢。

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.

最满意答案

您需要Form1的实例。 通常,如果您已显示此表单, Form1 form1 = new Form1()实例化它( Form1 form1 = new Form1() )。 然后,您可以对此实例进行操作并访问公共成员:

form1.ob1.status = 1;

另一种可能性是让你的Form2构造函数采用Form1实例:

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

然后当你在Form1中的某个地方并想要创建和显示Form2 :

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

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();

更多推荐

本文发布于:2023-04-29 02:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334451.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   对象   如何在   form   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!