Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I navigate between forms

I am a newbiest in c# and window form i am doing a project and i meet some problem

  1. how can i navigate forms within the window( i have a menu strip, when click it will show a item "Brand", so when i click it, it should open up within the window , i don't want something using the mdiparent/container, i have form1 and form2, then i put the menu strip in form1, which there is some thing inside form1, if use the mdiparent/container, the form1 content/thing will block the form2 )

2.i use the below code and the problem is i want to close the form1 which i click on " Brand" in the menu strip...but how???

public partial class Form1 : Form
{
    //  i put the menu strip in form1 design
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    }

    private void Check_Click(object sender, EventArgs e)
    {
        Form2 Check = new Form2();
        Check.Show();
    }
}
like image 908
cutexxxbabies Avatar asked Jun 24 '11 03:06

cutexxxbabies


2 Answers

You cannot just close the Form1 as it is the main form, but you can hide it. Use this.Hide().

private void Check_Click(object sender, EventArgs e)
{
    Form2 Check= new Form2();
    Check.Show();
    Hide();
}

[EDIT]

Not sure if this is what is asked. But...

There are many ways to implement navigation between forms, for example:

In Form1:

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

In Form2:

private void button1_Click(object sender, EventArgs e)
{
    var form1 = (Form1)Tag;
    form1.Show();
    Close();
}
like image 131
Alex Aza Avatar answered Oct 19 '22 13:10

Alex Aza


I think you should create usercontrols rather than different forms. Then you can add your usercontrols in your main panel according to the selection in the menu.

Initially something like below

this.panel.Controls.Clear();
this.panel.Controls.Add(new UserControl_For_Form1());

Once the user click some other selection in menu.

this.panel.Controls.Clear();
this.panel.Controls.Add(new UserControl_For_Form2());

If you really want to use the way that you are using at the moment. Below code will help.

Add a Form1 property for the Form2 and parse the form1 instance to the Form2 with its constructor.

public partial class Form2 : Form
    {
        private Form1 form1;

        public Form2(Form1 myForm)
        {
            InitializeComponent();
            form1 = myForm;
        }
    }

Show the form2 and hide the form1.

private void Check_Click(object sender, EventArgs e)
{
    Form2 Check= new Form2(this);
    Check.Show();
    Hide();
}

In form2 closing event now you can show the form1 instance which is in the form2 and close the form2.

Using of MDI form is another option for you.

like image 32
CharithJ Avatar answered Oct 19 '22 14:10

CharithJ