Managing multiple forms

Opening/Closing vs Showing/Hiding

Page 1 of 1

10 Replies - 9681 Views - Last Post: 27 October 2010 - 08:54 AM Rate Topic: -----

#1 jayxx   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 06-May 10

Managing multiple forms

Posted 26 August 2010 - 08:26 PM

I am writing a c# program using visual studio 2010 ultimate, with multiple forms (5 forms: one with a form selection on it, and four others with different things to do). I am wanting to be able to have a variable in form 1 that other forms can edit, and I am wanting to know whether form show/hide or open/close is better. I have this so far:

      Form2 form2 = new Form2();
            form2.Show();
            this.Hide();


I want this code to show form 2 and hide form1, but so that if I close form 2 (click on the X), the whole program stops running. As it is, it keeps running, and I assume this is because some forms are only hidden, not closed. But I tried:

      Form2 form2 = new Form2();
            form2.Open();
            this.Close();


but that didnt seem to make any difference. I google'd it, and it said to go to tools > options > Debugging > Break all processes when one process breaks. This sounds like not what I want, and it mustn't be, cos it didnt work. Can someone please tell me how to navigate between forms so that if I close the visible one, the whole program stops running, and I can edit my code straight away without having to press stop every time?

Is This A Good Question/Topic? 0
  • +

Replies To: Managing multiple forms

#2 Ionut   User is offline

  • D.I.C Lover
  • member icon

Reputation: 386
  • View blog
  • Posts: 1,057
  • Joined: 17-July 10

Re: Managing multiple forms

Posted 26 August 2010 - 11:30 PM

Quote

I am wanting to be able to have a variable in form 1 that other forms can edit

You need a class property
public class Form1 : Form
{
   private int FAnyVariable;
   
   public int AnyVariable
    {
        get {return FAnyVariable; }
        set {FAnyVariable = value;}
    }
}
...
   Form1 frm = new Form1();
   frm.AnyVariable = 5;
   MessageBox.Show(frm.AnyVariable.ToString());



The difference between Hide and Close is that close disposes any resources that a form uses.
If you want the whole application to close when you close form2, you should close the application's main form:
1. look in Program.cs, there is a line of code
 Application.Run(new FormX())
. This FormX is the main form and closing it will stop the process. So, if you manage the Form2's FormClosed event, you will get result you want.
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
           frm1.Close(); //you decide how to gain access to form1 object's reference, maybe through property
        }




Ionut
Was This Post Helpful? 0
  • +
  • -

#3 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6538
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Managing multiple forms

Posted 27 August 2010 - 07:15 AM

Quote

I am wanting to be able to have a variable in form 1 that other forms can edit,

Stop right there. Bad design.

It is not the job of form2 to directly affect anytyhing in another form. They should all be black boxes that know nothing of any other form. Having them directly make changes to each other is asking for trouble.

Form2 should raise an event saying "I've done this" or "I'm requesting this"... and nothing more. If form1 wants to react to that by changing a value in a variable then fine. Form1 is responsible for form1. Form4 is responsible for form4. That's it.


Quick and easy custom events
Bulding an application - Part 1
Building an application - Part 2
Was This Post Helpful? 3
  • +
  • -

#4 Imdsm   User is offline

  • D.I.C Regular
  • member icon

Reputation: 104
  • View blog
  • Posts: 362
  • Joined: 21-March 09

Re: Managing multiple forms

Posted 27 August 2010 - 11:10 AM

I will copy what I just wrote in another topic:

Quote

If you close the initial form it seems to close the program, so you hide it. However, if you then close the other forms, the program stays alive, so in the other 'main' form closing event you will want to either Application.Exit() out or show the other form again.

Good luck!

Was This Post Helpful? 0
  • +
  • -

#5 jayxx   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 06-May 10

Re: Managing multiple forms

Posted 07 September 2010 - 04:16 PM

View PosttlhIn, on 27 August 2010 - 06:15 AM, said:

Quote

I am wanting to be able to have a variable in form 1 that other forms can edit,

Stop right there. Bad design.

It is not the job of form2 to directly affect anytyhing in another form. They should all be black boxes that know nothing of any other form. Having them directly make changes to each other is asking for trouble.

Form2 should raise an event saying "I've done this" or "I'm requesting this"... and nothing more. If form1 wants to react to that by changing a value in a variable then fine. Form1 is responsible for form1. Form4 is responsible for form4. That's it.


Quick and easy custom events
Bulding an application - Part 1
Building an application - Part 2

Thanks for your concern, but I am simply discovering how c# works, not necessarily what I should be doing. I have, however, figured it out:
In Form1, the value I want the other forms to be able to edit, is called funds. This is how I create a method in Form1 for the other forms to call to display funds:
internal void ReloadFunds()
        {
            label_Funds.Text = funds.ToString("C0");
            Console.WriteLine(funds.ToString("C0"));
        }


Here is my call to show Form2:
Form2 frm2 = new Form2(this);
            this.Hide();
            frm2.Show();
            


Note how I passed "this" (Form1) to frm2. In the Form2 Initialize statement:
public Form2(Form1 callingForm)
        {
            InitializeComponent();
            frm1 = callingForm;
        }

This allows Form2 to see and use Form1 and all its code.

Here is my code to change funds in Form1, from Form2:
frm1.funds -= 25000;
            frm1.ReloadFunds();

to charge $25000 for showing Form2, and:
score = remTime * 2000;
            MessageBox.Show("Congratulations! You have won " + score.ToString("C0"));
            frm1.funds += score;
            frm1.ReloadFunds();
            frm1.Show();
            this.Close();

to reward user with funds depending on remaining time, shows Form1, and closes Form2.
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6538
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Managing multiple forms

Posted 07 September 2010 - 04:32 PM

Quote

Thanks for your concern, but I am simply discovering how c# works, not necessarily what I should be doing


It is of course your education and your call. Just keep in mind it is easier (and faster) to build proper habits and style from the beginning than to go back and break all the bad habits then learn the good ones.

Would you have been happy to learn to drive with one foot on the brake and one on the gas for a year - THEN realize that you should use the same foot for both gas and brake - forcing yourself to re-train your brain?


What you have done in your sample works. But its fragile. Form2 has to know everything about Form1. If you or a co-worker make a change to Form1 next year then all your other forms break. We refer to this as "tightly bound". They are so tightly integrated to each other they might as well be one object. It pretty much violates all the basic principals of object oriented coding where each class (and a form is a class) is a black box that is blind to the outside world. It should do its own job then yell "I'm done, here are the results", oblivious to whether or not someone is in the room listening and waiting for those results.

Picture a bingo parlor. Your code is the guy calling the numbers.
In your code the caller picks a number, then walks down to the first player and tells them to mark space N-14, then walks to the next player and tells them, then walks to the next player and tells them. It all happens sequentially and is the responsibility of the caller. So it is much slower.

In an event driven bingo parlor the ball caller can be blind (assuming braille balls). He just picks a ball and yells the number. There can be 100 players or zero. The caller doesn't have to know. All the players react to the event simultaneously. Its a ton faster.
Was This Post Helpful? 2
  • +
  • -

#7 jayxx   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 06-May 10

Re: Managing multiple forms

Posted 25 October 2010 - 06:24 PM

Thanks for the reply. (note, I am not forming habits, but learning how c# code works. I will be taking a programming degree at uni next year, and wanted to get a bit of a headstart in understanding the abilities of c#.)

Do you have any examples on how exactly for Form1 to "call out" to Form2, and vice versa, while being "blind" to what the other form does? This would help greatly, thanks.

Jayxx
Was This Post Helpful? 0
  • +
  • -

#8 erburrell   User is offline

  • D.I.C Head
  • member icon

Reputation: 10
  • View blog
  • Posts: 149
  • Joined: 22-December 09

Re: Managing multiple forms

Posted 26 October 2010 - 04:34 PM

Well, it depends on what you are having Form2 do. If Form2 simply opens and closes, you could create From2 with an OK and CANCEL buttons. You could then make the dialogresult for each of these OK and Cancel respectively. You then call From2 as such:

Form2 myNewForm2 = new Form2();
myNewForm2.ShowDialog();
if (myNewForm2.DialogResult == DialogResult.OK)
{
  //Do some stuff...
}


That way, Form2 is still a black box, but Form1 gets a response from it. If you want to get specific information from Form2, you can add public Properties and allow Form1 to get those values by adding the following code to Form2:

private string _myString;
public string MyString { 
  get { return _myString; }
}


Again, this provides some access to values within Form2, but keeps the forms separated as they should be.

Ed.
Was This Post Helpful? 0
  • +
  • -

#9 lordofduct   User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2668
  • View blog
  • Posts: 4,786
  • Joined: 24-September 10

Re: Managing multiple forms

Posted 26 October 2010 - 04:52 PM

View PosttlhIn, on 07 September 2010 - 03:32 PM, said:

Quote

Thanks for your concern, but I am simply discovering how c# works, not necessarily what I should be doing


It is of course your education and your call. Just keep in mind it is easier (and faster) to build proper habits and style from the beginning than to go back and break all the bad habits then learn the good ones.

... snip


Ditto

I want to put emphasis on what t1hIN'toq says in this thread.

It's actually one of my biggest complaints about VB.Net (I know this is a C# thread, but it's my gripe). The language promotes this awful practice by creating global values for each form that is accessible as the forms class name. It grants access to it from anywhere in the code. This drives me up the wall as I'm in a project with some other developers that is in VB.Net and they continually access this freakin' value and then wonder why shit goes all wrong.

Why the team that designs VB didn't think to at least put it in some other namespace or something is beyond me. Like how you have the My.Settings in VB... My.formMain wouldn't bother me as much... at least then the syntax screamed you were accessing some global. Then I would just tell the team, "if you say My, and don't follow it by any of these approved names (Settings, etc), then I will personally smack you in the face."... and then I could just do a nice ctrl+f sweep of the code for My.f (because our forms are all named starting with an f) and fix all the issues. But noooooooo... I hate coming into a project mid way. I've spent over a month locating references to fMain this and fMain that... and I'm still not done.


::hopes to never have to write VB again::

/rant


anyways, it's bad practice, don't do it, think about how the preexisting forms function in .Net. Things like the various dialog boxes and the sort. They hand back data through properties and events... not this cross dependent manner that can create one giant rats nest of code.

This post has been edited by lordofduct: 26 October 2010 - 04:55 PM

Was This Post Helpful? 0
  • +
  • -

#10 Robin19   User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: Managing multiple forms

Posted 27 October 2010 - 08:24 AM

Here is another change to make:
        void ShowForm2()
        {
            Step1();
            Form2 form2 = new Form2();
            this.Hide();
            form2.Show();
            Step5();
        }

This function will perform Step1. Then it will create a Form2 object. Then it hides itself. Then it shows form2. Then it performs Step5. It will do these steps as quickly as possible. It will reach the end of this code block (unless Step5 slows it down) before your eye sees Form2. If you want that to happen, this is fine. I like to use ShowDialog. ShowDialog will not finish processing until the form is closed. Then you can do something like this:
        void ShowForm2()
        {
            Step1();
            Form2 form2 = new Form2();
            this.Hide();
            form2.ShowDialog();
            this.Show();
            Step5();
        }

Now it will do Step1. Create a Form2 object. Hide itself. Show form2 and wait until form2 closes. After form2 closes, it continues processing and shows itself. Then it does Step5. I think this is one of the things you wanted solved, but I do agree with the others about making black boxes.
Was This Post Helpful? 0
  • +
  • -

#11 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6538
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Managing multiple forms

Posted 27 October 2010 - 08:54 AM

View PostRobin19, on 27 October 2010 - 07:24 AM, said:

Here is another change to make:
        void ShowForm2()
        {
            Step1();
            Form2 form2 = new Form2();
            this.Hide();
            form2.Show();
            Step5();
        }

This function will perform Step1. Then it will create a Form2 object. Then it hides itself. Then it shows form2. Then it performs Step5. It will do these steps as quickly as possible. It will reach the end of this code block (unless Step5 slows it down) before your eye sees Form2. If you want that to happen, this is fine. I like to use ShowDialog. ShowDialog will not finish processing until the form is closed. Then you can do something like this:
        void ShowForm2()
        {
            Step1();
            Form2 form2 = new Form2();
            this.Hide();
            form2.ShowDialog();
            this.Show();
            Step5();
        }

Now it will do Step1. Create a Form2 object. Hide itself. Show form2 and wait until form2 closes. After form2 closes, it continues processing and shows itself. Then it does Step5. I think this is one of the things you wanted solved, but I do agree with the others about making black boxes.


Another approach is to not use multiple forms at all, but instead use UserControls. I don't like the user experience of having lots of different forms opening and closing. Very Windows 3.51 if you ask me. I like having my one form open... moved and sized where I want it (monitor number 4 maybe)... then have the changes take place there.

I usually place a panel, on my form then move all my UserControls in and out of it. With the addition of a simple property it becomes rather easy.

ControlsCollection Workspace
{
   get
      {
         return  myMainPanel.Controls;
      }
}

#region Constructors
public void Form1 : Form
{
    public Form1
    {
      InitializeComponents();
      Workspace.Clear();
      Workspace.Add(myLogInUC);
}

void SettingsMenuItem_Click(sender object, eventargs e)
{
    Workspace.Clear();
    Workspace.Add(mySettingsUC);
}


Using this technique there is no ugly flashing of one form hiding and one showing... no problem with the main application being on monitor 3, but your new form opening on monitor 1 etc. etc. It provides a single window into your application. Its smooth.


The nice thing about UserControls is that if you want to turn one into a form all you have to do is make a new form, add the user control, size the form to the UserControl, then show the Form. You can turn a UC into a form, or use it as a UC on an existing form. To me it just feels like I can get more use out of it.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1