Search code examples
c#winformssubform

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


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
}

Solution

  • 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
        }
    }