Reputation: 63
I have 5 different forms. First form is the MainForm and others are childForms.
The MainForm have params that I can change whenever I want and child forms have different tasks that takes the object from mainform.
How can I pass and then update that object from mainform to childforms ?
I found solution with event, but it updates mainform from childforms. Here
MyObject :
public class BarcodeModel
{
public string XCoord { get; set; }
public string YCoord { get; set; }
public bool IsRequired{ get; set; }
}
MainForm :
private void btnOneFile_Click(object sender, EventArgs e)
{
Form1File newForm = new Form1File();
BarcodeModel model = new BarcodeMode();
OpenChildForm(newForm, sender);
}
private void comboBoxClients_SelectedIndexChanged(object sender, EventArgs e)
{
model.XCoord = "DynamicInfo";
model.YCoord = "DynamicInfo";
model.IsRequired = true;
// every time it changes I want to send data to child form
}
ChildForm:
private void btnStart1File_Click(object sender, EventArgs e)
{
// here I want to have updated object
}
Any solutions ? Thank you.
Upvotes: 1
Views: 161
Reputation: 216293
You can use a custom event raised by the MainForm. So every client that has an interest in knowing changes to the Barcode model AND has an instance reference to the MainForm could subscribe the event and receive an updated version of the Barcode instance handled by the MainForm.
In the main form declare the custom event so anyone could subscribe to it
public delegate void ModelChangedHandler(Barcode model);
public event ModelChangedHandler BarcodeChanged;
Now, still in the MainForm raise the event when you change the model properties.
private void comboBoxClients_SelectedIndexChanged(object sender, EventArgs e)
{
model.XCoord = "DynamicInfo";
model.YCoord = "DynamicInfo";
model.IsRequired = true;
BarcodeChanged?.Invoke(model);
}
In the child form you need to have a constructor that receives the MainForm instance and save it to an internal property. At the same time you subscribe the event using an handler internal to the child form
public class Form1File : Form
{
MainForm _parent = null;
public Form1File(MainForm main)
{
_parent = main;
_parent.BarcodeChanged += modelChanged;
}
The handler receives the updated model and does what's needed with the new model info
public void modelChanged(Barcode model)
{
.....
}
}
Upvotes: 1