How can I navigate between forms

I am new to C # and the window form I am doing a project and I am encountering some kind of problem.

  • how can I navigate the forms inside the window (I have a menu bar, when I click it it will show the β€œBrand” element, so when I click on it it will open in the window, I don’t want to use mdiparent / container, I have there is form1 and form2, then I put the menu bar in form1, in which there is some kind of thing inside form1, if mdiparent / container is used, the content / subject of form1 will block form2)

2.i use the code below, and the problem is that I want to close form1, which I click on "Brand" in the menu bar ... 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(); } } 
+6
source share
2 answers

You cannot just close Form1 as this 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 given. 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(); } 
+17
source

I think you should create usercontrols, not different forms. You can then add your custom controls to your main panel according to your selection in the menu.

Initially something like below

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

As soon as the user clicks on another choice in the menu.

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

If you really want to use the way you are currently using. Below is the code.

Add the Form1 property for form 2 and parse the instance of form1 in Form2 with your constructor.

 public partial class Form2 : Form { private Form1 form1; public Form2(Form1 myForm) { InitializeComponent(); form1 = myForm; } } 

Show form2 and hide the form.

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

In the closing event of form 2, you can now show an instance of form1, which is in form2, and close form 2.

Using an MDI form is another option for you.

+2
source

Source: https://habr.com/ru/post/891261/


All Articles