I have a main form which allows opening another forms (at this moment up to 3 form).
I am using following code to open a form from main form:
public partial class network : Form
{
p1 _p1 = new p1();
p2 _p2 = new p2();
public network()
{
InitializeComponent();
}
private void Phone1_Click(object sender, EventArgs e)
{
_p1.Show();
//Phone1off.Visible = true;
//networklog.Items.Add("Phone 1 added");
}
above code working fine at the moment.
Now, the problem is when let's say I have opened two forms from main form and have type something in the child form1 then want to display it in child form2. I am unable to do it.
at this moment I have coded as below to achieve this:
public string TextBoxValue
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
private void button2_Click(object sender, EventArgs e)
{
p2 _p2 = new p2();
textBox1.Text = "";
textBox1.Text = "Calling Phone 2";
_p2.TextBoxValue = "Phone 1 Calling";
}
also for your information all my child forms will have same layout. so I am inheriting all from 1 design (say form1: form2)
I will appreciate your response
I would recommend using .showDialog() instead of .show(). This way, the data in _p2 doesn't disappear when _p2 closes. You'll still be able to access the data from _p2 in _p1. Before you call .showDialog(), you can set the values of the variables of _p2 using the data from _p1. Then, when you do finally call .showDialog(), it will display all the data you set earlier.
You are looking for DataBinding to have a Model (a simple class, List or Datatable) being watched by multiple controls.
Model
First have a class that will act as the model:
Compile this so the designer can find that class when you add ...
BindingSource
... to the designer of your Network Form:
Set the
DataSource
property to an object and choose thePhoneModel
class.Set the
Modifiers
property toProtected
Do the same for your base class called
P
.On the
TextBox
select in the properties theDataBinsdings settings
:Subclassed form handling
I'm not sure why have two different classes but let's keep that as a fact.
Add an constructor to each of your classes that will accept the
BindingSource
instance from the caller. We use that instance to update the per form BindingSource.Do this for every form you have that needs to synchronize its values
Wire your Network form to the P1 and P2 instances
In the click events of your buttons on the Network form start P1 or P2 by providing the
BindingSource
in the constructor:And have your model instantiated, I used the Form_Load event to do that.
That is all there is. When you enter values in one of the TextBoxes all values on all open forms will get updated due to the BindindingSource that updates all controls that it is bounded to as can be seen in this demo: