如何从另一个表单访问一个表单的属性?

我有2个WinForms,在Form1中我声明了这个:

public int NumberOfContacts { get; set; } 

我需要从Form2访问该属性。

这是关于从其他表单加入表单成员的常见问题,我将假设您要从Form1的当前活动实例访问NumberOfContacts,在这种情况下,您将简单地,就像您在您的声明中所声明的那样:

Form1

  public partial class Form1 : Form { public int NumberOfContacts { get; set; } public Form1() { InitializeComponent(); } } 

Form2中

 public partial class Form2 : Form { public Form2() { InitializeComponent(); // ActiveForm will give you access to the current opened/activated Form1 instance var numberOfContacts = ((Form1) Form1.ActiveForm).NumberOfContacts; } } 

这应该工作。

打开Form2使用以下代码:

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

在你的Form2:

 var value = ((Form1)Owner).NumberOfContacts; 

如果您已从form1创建了form2的实例,则可以将其设置为:

 Form2 form2 = new Form2(); form2.NumberfOfContacts = this.NumberOfContacts; form2.Show(); 

您还可以将form1.NumberOfContacts的值传递给form2的构造函数,如下所示:

 Form2 form2 = new Form2(this.NumberOfContacts); form2.Show(); 

Form2类:

 public int NumberOfContacts { get; set; } public Form2(int numberOfContacts) { NumberOfContacts = numberOfContacts; } 

如果要访问和更改其他表单属性,可以使用以下方式:

 private void button1_Click(object sender, EventArgs e) { frm_main frmmain = new frm_main(); frmmain.Visible = true; frmmain.Enabled = true; }