How to open a new form from another form

Dinesh picture Dinesh · Oct 19, 2010 · Viewed 448.1k times · Source

I have form which is opened using ShowDialog Method. In this form i have a Button called More. If we click on More it should open another form and it should close the current form.

on More Button's Click event Handler i have written the following code

MoreActions objUI = new MoreActions (); 
objUI.ShowDialog();
this.Close();

But what is happening is, it's not closing the first form. So, i modified this code to

MoreActions objUI = new MoreActions (); 
objUI.Show();
this.Close();

Here, The second form is getting displayed and within seconds both the forms getting closed.

Can anybody please help me to fix issue. What i need to do is, If we click on More Button, it should open another form and close the first form.

Any kind of help will be really helpful to me.

Answer

Johann Blais picture Johann Blais · Oct 19, 2010

In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:

// MainForm
private ChildForm childForm;
private MoreForm moreForm;

ButtonThatOpenTheFirstChildForm_Click()
{
    childForm = CreateTheChildForm();
    childForm.MoreClick += More_Click;
    childForm.Show();
}

More_Click()
{
    childForm.Close();
    moreForm = new MoreForm();
    moreForm.Show();
}

You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.