Open new form and close the current Windows Form using C# and VB.Net

Last Reply 4 months ago By pandeyism

Posted 4 months ago

I am trying to open "Form2" from "Form1" button click and close the Form1

But it is not happening, "Form1" remain open while "Form2" is opened and close both form when I closed "Form2"

Here is the code i have used in form1 button click event

Dim frm As New Form2()
frm.ShowDialog()
Me.Close()
Me.Dispose()

 

Posted 4 months ago

Hi satabeach,

Refer below sample.

Code

C#

Form1.cs

private void Open(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    f2.Owner = this;
    f2.Show();
    this.Hide();
}

Form2.cs

private void Close(object sender, EventArgs e)
{
    this.Owner.Close();
}

VB.Net

Form1.vb

Private Sub Open(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim f2 As Form2 = New Form2()
    f2.Owner = Me
    f2.Show()
    Me.Hide()
End Sub

Form2.vb

Private Sub Close(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Me.Owner.Close()
End Sub

Screenshot