Question How to access an instance of a class's object (for example Form form;) from another form?

Joined
Sep 26, 2022
Messages
16
Programming Experience
1-3
I have a form instance that was created on menustrip button click. So I am in a form that contains a menustrip and I am openin another form. When I close the newly opened form (which was created by clicking the menu strip), I want to set the -for ex: Form form; object instance's value to null on close.

However the on_closing and on_close methods are not found in this form itself, they are not in the menustrip form so I am not able to access the form instance and set it to null value from the another form.
Here is the code :

Form2 code:
C#:
public Form3 form3;
        private void müşteriGirişiToolStripMenuItem_Click(object sender, EventArgs e)
        {
           if (form3 == null)
           {
               form3 = new Form3(musteriler);
               form3.MdiParent = this;
               form3.Show();
           }
        }
Form3 code:
C#:
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
        {
            form3 = null;
        }
How do I reach the form3 object instance that is inside the form3, from form2 event method and set it to null on close??
 
Last edited:
You can add event handler where you create the form:
C#:
form3 = new Form3(musteriler);
form3.FormClosed += Form3_FormClosed;
...

also remember to remove handler before you release the reference:
C#:
form3.FormClosed -= Form3_FormClosed;
form3 = null;
 
You can add event handler where you create the form:
C#:
form3 = new Form3(musteriler);
form3.FormClosed += Form3_FormClosed;
...

also remember to remove handler before you release the reference:
C#:
form3.FormClosed -= Form3_FormClosed;
form3 = null;
It does not see the form3 object instance in the first place.
 
1670523383601.png
 
Form3_Closed method goes in your Form2 class where you handle the event.

1670526867559.png

No, Form2 code!
 

Latest posts

Back
Top Bottom