Reputation: 57
I have been trying for a while for two forms to share data with each other. In this case, inheriting data from form 2 to 1. I have tried several methods and this method is the one that I have managed to implement best.
The problem is that it does not finish working, in the second form the value obtained is always 0, surely it is a small detail, but I really do not know how to end this.
Any attempt to help is greatly appreciated :)
Form1:
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);
}
}
}
}
Upvotes: 0
Views: 750
Reputation: 717
You have instantiated the class cntr()
two times. Therefore you have two objects working in their own instance, without knowing that the other is already created.
You can deal with this case by instantiating one shared class. Instantiate in your main form the class cntr()
, then tell to your second class where is your instance.
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);
}
}
}
}
Upvotes: 1