0

So, I'm trying to close the current form (form1) AND another form (form2) too then show form3.

whatsapp wForm = new whatsapp();
wForm.Close();
this.Close();

login logForm = new login();
logForm.Show();

I had the login form hidden on earlier stages (this.Hide()), There is a button on the login form that shows the whatsapp form, and the whatsapp form has a button that shows the setting form (which is the current form above form1), which I showed using (settings f = new settings(); f.DialogShow();)

Now I'm trying to close both the settings and whatsapp forms, and show the login form.

CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108
Oussama Essamadi
  • 358
  • 8
  • 15

2 Answers2

1

You can get in to a real mess when one form controls another, unless there is a definite parent/child relationship.

I would suggest that you have a single controlling object, e.g. a FormController class (this is something that you would create this yourself), and have the presentation of your two forms controlled from there.

As well as tidying up the relationship between your objects, you get a better single responsibility mapping - what I mean by that is it is should not be the responsibility of one form to control another. Instead, when an action is performed on one form it simply raises an event to tell anybody that cares that the action has occurred. If nobody cares then that's the end of that, but in this instance you would have a FormController register its interest in the event, and when raised it would then be the window controller's job to listen to that event and handle it accordingly, i.e. in this case affecting the visibility/existence of another form.

Here's a very crude example of what I mean:

public class FormController
{
    private readonly WhatsappForm whatsappForm = new WhatsappForm();
    private readonly LoginForm loginForm = new LoginForm();

    public FormController()
    {
        loginForm.SomeActionPerformed += HandleLoginActionPerformed;
    }

    private void HandleLoginActionPerformed(object sender, EventArgs e)
    {
        whatsappForm.Show();
    }
}

Where SomeActionPerformed is an event raised by the login form, so:

partial class LoginForm
{
    ...

    public event EventHandler SomeActionPerformed;
}
LordWilmore
  • 2,829
  • 2
  • 25
  • 30
  • 1
    You raise very important points, so I already gave my upvote. But especially for someone who's likely a new user, having some sample code for your FormController and how to use it would make this an even better answer. – Scott Mermelstein Dec 22 '17 at 13:48
0

I suspect this post here will answer this for you perfectly: Open Form2 from Form1, close Form1 from Form2

Using a constructor on the child form that takes in relevant parent forms as arguments will allow you to access the parent forms Close() method within the child.