如何获取包含在其他窗体类/C#Windows窗体中的值



我已经尝试了一段时间让两个表单相互共享数据。在这种情况下,将数据从表单2继承到1。我尝试了几种方法,这种方法是我实现得最好的方法。

问题是它没有完成工作,在第二种形式中,获得的值总是0,当然这是一个小细节,但我真的不知道如何结束。

任何帮助的尝试都将不胜感激:(

表格1:

using System;
using ...;
namespace Name
{
public partial class Form1 : Form
{
cntr val = new cntr();
}
/// omited code that modifies val.count
public class cntr
{
public int count_ = 0;
public int count
{
get
{
return count_;
}
set
{
count_ = value;
}
}
}
}

Form2:

using System;
using ...;
namespace Name
{
public partial class Form2 : Form
{
cntr aye = new cntr();
public Form2()
{
InitializeComponent();
}
private async void Read()
{
while (true) /// updating the .Text every 5 seconds
{
Box2.Text = aye.count;
await Task.Delay(500); 
}
}
}

}

您已经实例化了两次类cntr()。因此,您有两个对象在它们自己的实例中工作,而不知道另一个已经创建。

您可以通过实例化一个共享类来处理这种情况。在主窗体中实例化类cntr(),然后告诉第二个类实例在哪里。

namespace Name
{
public partial class Form1 : Form
{
cntr val = new cntr();
// Tell to your second form to use this shared object
Form2 form2 = new Form2(val);
form2.Show();
}
public class cntr { ... }
public partial class Form2 : Form
{
private cntr _aye;
public Form2(cntr sharedCntr)
{
// Save the shared object as private property
_aye = sharedCntr;
InitializeComponent();
}
private async void Read()
{
while (true)
{
Box2.Text = _aye.count.ToString();
await Task.Delay(500);
}
}
}
}

最新更新