Przemysław Lunic
Przemysław Lunic

Reputation: 391

C# Switching between two windows forms

I have two forms. In first I have button forwarding me to second form and hiding the first one with this.Hide();

It looks like this:

        Form1Streamer f1 = new Form1Streamer();
        f1.Left = this.Left;
        f1.Top = this.Top;
        f1.Size = this.Size;
        f1.Show();
        this.Hide();            
        checkBox1.Checked = false;

It also takes it's position but it's not about it. In second form I have a button which should after clicking Go back to the hidden form and make it visible again, but I can find no solution how to access it's properity. I have some ideas but don't really know how to tag it. Any help appreciated.

Upvotes: 2

Views: 86

Answers (2)

Pankaj Prakash
Pankaj Prakash

Reputation: 2418

You need to pass the reference of the first form to the second form in order to call any method of first form. Here is a simple Example that will demonstrate.

Below is my first form class

using System;
using System.Windows.Forms;

namespace Test_Desktop
{
    public partial class FirstForm : Form
    {
        public FirstForm()
        {
            InitializeComponent();
        }

        private void showSecondFormButton_Click(object sender, EventArgs e)
        {
            SecondForm secondform = new SecondForm(this); //Passing the reference of current form i.e. first form
            secondform.Show();
            this.Hide();       
        }
    }
}

And here is my second form class

using System;
using System.Windows.Forms;

namespace Test_Desktop
{
    public partial class SecondForm : Form
    {
        private FirstForm firstForm = null;

        public SecondForm()
        {
            InitializeComponent();
        }

        ///
        /// Overriding constructor
        ///
        public SecondForm(FirstForm firstForm)
        {
            InitializeComponent();
            this.firstForm = firstForm;
        }

        private void showFirstFormButton_Click(object sender, EventArgs e)
        {
            if(firstForm!=null)
            {
                firstForm.Show();

                //
                //Do some processing
                //

                this.Dispose(); 
            }
        }
    }
}

Upvotes: 2

Anup Sharma
Anup Sharma

Reputation: 2083

You need the reference of hidden form in the second form. For that, change the constructor of Second form like this

public Form1Streamer(Form firstform)
{
   InitilizeComponent();
   this.firstForm=firstform;
}

private FirstForm firstForm;

Now you can show the First Form using reference firstForm

In first form, you need to change this code

Form1Streamer f1 = new Form1Streamer();

to

Form1Streamer f1 = new Form1Streamer(this);

Upvotes: 0

Related Questions