Home > Enterprise >  How to pass variable value between identical instances of WindowsForm
How to pass variable value between identical instances of WindowsForm

Time:03-09

I have a base form From1. In the form when button is clicked, new form From2 is created.

private void Button_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    f2.Show();
}

User can create several instances of From2. In From2 user can set a value in textBox and click a button. Once it is clicked, value from textBox has to be somehow transferred to all other created instances of From2. How can I do that?

CodePudding user response:

Step 1: remember all forms you created.

private void Button_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    allForms.Add(f2);          // remember it
    f2.Show();        
}

Step 2: when the value changes, update all remembered forms

private void textbox1_TextChanged(object sender, EventArgs e)
{
    foreach (Form2 form in allForms)
    {
        form.MyValue = textbox1.Text;
    }
}

Just write the code like that, then let the IDE help you creating the properties and adjust the visibility accordingly, e.g. have the IDE help you implement a property in Form2 that sets the text

string MyValue 
{
    set
    {
        anotherTextbox.Text = value;
    }
}

You'll then notice that you need some more stuff, probably.

Step 3: remove the form from the list when it is closed.

private void Button_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    allForms.Add(f2);
    f2.Closed  = OnClose;   // Method to be called when form is closed
    f2.Show();        
}

private void OnClose(object sender, EventArgs e)
{
    Form2 form = (Form2) sender;
    form.Closed -= OnClose;   // Unregister event handler
    allForms.Remove(form);    // remove it
}
  • Related