views:

45

answers:

2

In C#, using CF, how do you display a window that already has a previous instance loaded into memory?

Example: Form1 has a textBox1 and a button. Some text is typed into texBox1. The button click of Form1 loads Form2 which also has a button. Clicking Form2's button calls Form3. How do you call the already running instance of Form1 to call it's updateField method for example?

+1  A: 

Simply keep a reference to the instance of Form1 somewhere - e.g. pass it into Form2 when you construct it, and then Form2 can pass it to Form3 to use.

There's nothing special about UI controls here - just think what you'd do if you wanted to access any other kind of object.

Jon Skeet
actually, teh situation is more complicatedI have a custom control class, and in form1 I make more instances from it. and this custom control calls the form2. so the main problem is ho to access the custom control's formthe customcontrol's parent is a listbox.it should work: control.Parent.Parent?
arnoldino
Have you tried using `Control.FindForm()`? If that doesn't work, you should go back to what I suggest: pass the information everywhere that you need it. Again, think what you'd do if you weren't dealing with a UI situation.
Jon Skeet
+1  A: 

You do this with events. Form3 should have a public property that exposes the value and an event that it fires when the value changes. Form2 should subscribe to the event so it can track changes. Repeat to let Form1 know.

This de-couples the classes, Form3 doesn't have to know anything about Form2 nor Form1, only that somebody might be interested in the property value. Refactoring these parent form classes cannot break Form3. Note how the Windows Forms control classes work the same way.

Hans Passant
Now *that* is a correct answer. How can one Form get info from another directly? It shouldn't. I'd probably even suggest that a Controller or Presenter be the intermediary, then the Forms don't even need to know of each other's existence.
ctacke