Bonaca
Bonaca

Reputation: 313

c# winforms - how to access ParentForm from ChildForm

I readed manu articles about this, but - still confused.

from Form1 I open Form2:

new Form2().Show();

On Form2.ClosingEvent I need:

Form1.TextBox1.Visible = false;

What code and exactly where should I put - to achieve this ?

Upvotes: 0

Views: 10612

Answers (3)

Cody Gray
Cody Gray

Reputation: 244682

The problem is that, the way your code is currently structured, your instance of the Form2 class knows nothing about your instance of the Form1 class. Therefore, it cannot access properties or call methods on the other object. Remember that Form1 and Form2 are the names of classes, not objects.

The hacky solution would be to add a public field to your Form2 class that holds a reference to your Form1 object. You would fill in that field after you create an instance of your Form2 class, but before you call the Show method.

The next problem you'll run into is that, by default, controls on a form are private, which means that only code inside of the class that defines the form can access them. They cannot be accessed or manipulated from code inside of a different class.

The design you have is fundamentally broken from an object-oriented perspective. One class should not be manipulating or accessing private members of another class.

If anything, you should be handling this all in Form1. Modify the Form2 class to raise an event when it gets closed, and then subscribe to that event from Form1. Inside of the Form1 event handler method, hide the textbox.

The quick and dirty solution would be to switch to the ShowDialog method, which shows another form and blocks execution until that form gets closed. Then you could write:

// Create an instance of your Form2 class and show it as a modal dialog
using (var f = new Form2())
{
    f.ShowDialog(this);
}

// When the ShowDialog method returns, the Form2 form has closed, so
// you can go ahead and change the visible state of your control on Form1.
this.TextBox1.Visible = false;

However, the disadvantage of modality is that the user cannot interact with Form1 while Form2 is open. It's not clear from your question whether or not that is workable. If not, I recommend the previous solution, which involves raising an event. Either way, I highly recommend that you pick up a book on object-oriented programming in C#. Design like this is hard to fix later if you get it wrong.

Upvotes: 8

Sadaf
Sadaf

Reputation: 602

On Form2.ClosingEvent

Form1 parentForm = Application.OpenForms["FormName"] as Form1;
if (parentForm != null)
 {
    parentForm.TextBox1.Visible = false;
 }

make sure that on form1 TextBox1 is public

Upvotes: 2

user703016
user703016

Reputation: 37945

You can access your parent form using, well, ParentForm.

In this case ((Form1)ParentForm).TextBox1.Visible = false;, assuming TextBox1 is visible from the outside.

Upvotes: 6

Related Questions