Click here to Skip to main content
15,937,004 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to click on the button and go to Form2, and close current Form1. When I complete work on Form2, I want to click on Return button and return to Form1.

What I have tried:

Code in button from Form1 -> Form2

Form2 form2 = new Form2();

Code in button from Form2 -> Form1

Form1 form1 = new Form1();

I am getting error message:
System.ArgumentException: 'An item with the same key has already been added.'

I am using Mediator class
Updated 15-Apr-22 0:54am
Maciej Los 24-Jun-19 16:10pm    
WinForm or WPF?

to Do it right specilly if you set the MDIParent and if the first page is a Search Page.
as below

1- in the second form create Form variable
Form f;
2- then sent the veriable as below
internal void SetPrevForm(Form p)
3- in the first form call it as below
in the Button click event do as below

Form2 f = new Form2()

4- in the close button at Form2;
Share this answer
//try should work just fine

//from Form1 -> Form2

Form2 form2=new Form2();

//from Form2 -> Form1

Form1 form1=new Form1();
Share this answer
Richard MacCutchan 26-Jun-19 6:04am    
You are creating a new Form1 object instead of going back to the original.
Note: Form1 stays hidden, but wasn't closed.


You can check if Form1 is already opened by using Application.OpenForms Property (System.Windows.Forms) | Microsoft Docs[^]

Form frm = Application.OpenForms["Form1"]; //it should works

Note: please, read carefully Security section.


There's a collection: Application.Current.Windows
Application.Current.Windows.OfType<Window>().Where(x => x.Name == "Form1").FirstOrDefault()
Share this answer
If you keep switching back and forth between windows then you would get that error if you were trying to re-instantiate form1 or form2 when there was already an instantiated object for it. I tend to overcome this to check if the object exists already before I try to make a new one.
Share this answer
Sinisa Janjetovic 24-Jun-19 15:54pm    
Thank you, I also assumed that, but how to solve the issue?
AnotherKen 24-Jun-19 21:17pm    
I tend to use a boolean variable to store the object's existence state in. So I would do something like:

if !form1Exists
Form1 form1 = new Form1();
form1Exists = TRUE;

I would declare the boolean variable form1Exists and probably form2Exists also as global variables, that way I don't have to worry about loosing the value if the routine that sets it goes out of scope.

I would also set that value to false if I knew that form was closed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900