tags:

views:

326

answers:

4

now,i have two form,called form1 and form2,in the form1 there's a button,when i click it,then open the form2 question: in the form2,i want to creat a button when i click it,the form2 close and the form1 close.how to do? thx

A: 

Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.

Justin Ethier
Is there not an easier way? I know that in VB.NET, it's as easy as calling frmScores.show() or frmMain.hide(), but I've never looked at C#.
Christian Mann
Sure - Then you can use SiN's solution.
Justin Ethier
+1  A: 

Form1:

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2(this);
        frm.Show();
    }

Form2:

public partial class Form2 : Form
{
    Form opener;

    public Form2(Form parentForm)
    {
        InitializeComponent();
        opener = parentForm;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        opener.Close();
        this.Close();
    }
}
SiN
thank you!I solved this problem with your solution
hcemp
@hcemp, if this solved your problem, be sure to upvote and mark it as your accepted answer.
Anthony Pegram
A: 

on the form2.buttonclick put

this.close();

form1 should have object of form2.

you need to subscribe Closing event of form2.

and in closing method put

this.close();
Ram
A: 

if you just want to close form1 from form2 without closing form2 as well in the process, as the title suggests, then you could pass a reference to form 1 along to form 2 when you create it and use that to close form 1

for example you could add a

public class Form2 : Form
{
    Form2(Form1 parentForm):base()
    {
        this.parentForm = parentForm;
    }

    Form1 parentForm;
    .....
}

field and constructor to Form2

if you want to first close form2 and then form1 as the text of the question suggests, I'd go with Justins answer of returning an appropriate result to form1 on upon closing form2

Zenon