Click here to Skip to main content
14,334,138 members
Rate this:
Please Sign up or sign in to vote.
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();
this.Hide();
form2.Show()


Code in button from Form2 -> Form1

Form1 form1 = new Form1();
this.Hide();
form1.Show()


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


I am using Mediator class
Posted
Updated 25-Jun-19 20:16pm
Comments
Maciej Los 24-Jun-19 16:10pm
   
WinForm or WPF?
Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
   
Comments
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.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Note: Form1 stays hidden, but wasn't closed.

WinForm:


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
frm.Show();


Note: please, read carefully Security section.

WPF:


There's a collection: Application.Current.Windows
Application.Current.Windows.OfType<Window>().Where(x => x.Name == "Form1").FirstOrDefault()
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 3

//try this...it should work just fine


//from Form1 -> Form2

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


//from Form2 -> Form1

this.hide();
Form1 form1=new Form1();
form1.Show();
   
Comments
Richard MacCutchan 26-Jun-19 6:04am
   
You are creating a new Form1 object instead of going back to the original.

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100