How can you pass the state of a variable to a sub-form?

116 Views Asked by At

I have a form which contains a bool unitConnected. How can I pass the state of this boolean to a sub-form which I create and open at the press of a button?

Main form code:

// Global variable
public bool unitConnected = false;

private void buttonOpenSubForm_Click(object sender, EventArgs e)
{
    unitConnected = true;

    SubForm subForm= new SubForm();

    if (subForm.ShowDialog(this) == DialogResult.OK)
    {
        // Do something
    }
}

Sub-form code:

private MainForm mainForm = new();

public SubForm()
{
    InitializeComponent();
}

private void SubForm_load(object sender, EventArgs e)
{
    if (mainForm.unitConnected) // Do something
}
2

There are 2 best solutions below

0
Slash On BEST ANSWER

Answer by @Jon Skeet (in comments): "You can add a parameter to the constructor, then call new SubForm(this). Or if you only need to know about unitConnected, pass that into the constructor instead."

Sub-form:

private MainForm mainForm = new();

public SubForm(Form1 mainForm)
{
    InitializeComponent();
}

Main form:

public bool unitConnected = false;

private void buttonOpenSubForm_Click(object sender, EventArgs e)
{
    unitConnected = true;

    SubForm subForm= new SubForm(this);

    if (subForm.ShowDialog(this) == DialogResult.OK)
    {
        // Do something
    }
}
0
Tatsuya On

As I understand it, you want to create something like a MessageBox where you will open a form containing specific information and in the end you will choose "OK" or "Cancel". If this is your intention, you should follow the following steps.

Step 1:

 private void button1_Click(object sender, EventArgs e)
 {
     SubForm sub = new SubForm();
     if (sub.ShowDialog(this) == DialogResult.OK)
     {
        //Your Code
     }
  }

Step 2:

In the "SubForm" model, add a button and set the DialogResult property of this button to any value I choose as "Ok".

Note that if you want to receive any values from the "SubForm" model, set up a mediator class of type "static" and enter the properties and functions you need in order to access these values from anywhere in a excellent manner.