leimelson06 leimelson06 - 4 months ago 22
C# Question

Closing a form on another form?

A have a form that will show another form when you click logout. I want to close or hide both forms when you click yes and it will go to my login form. Any help would be appreciated.

enter image description here

Answer

You can use Form's Owner property to set child form's owner:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.Owner = this;
        form2.ShowDialog();
    }
}

Then in your secondary form you close it:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (this.Owner != null)
            this.Owner.Close();
    }
}