Search code examples
c#winformsformspublic-method

How to modify a Form and refresh it from another Form


I use two Forms:

Form1 contains button1

Form2 contains button2 and Panel1

My project starts using Form2. Then I click on button2 to show Form1

    private void button2_Click(object sender, EventArgs e)
    {
        Form1 Frm = new Form1();
        Frm.Show();
    }

Then on Form1, I click on button1 to hide Panel1 on Form2

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 FormInstance = new Form2();
        FormInstance.displayInit();
        FormInstance.Refresh();
    }

displayInit() is a method inside Form2:

    public void displayInit()
    {
        panel1.Visible = false;
    }

But the panel is not hidden, due to a refresh issue, any idea please ?


Solution

  • The standard way of having two forms (or any two classes) talk to each other is with events.

    In your case, add this to the top of the Form1 code:

    public event ClosePanelHandler ClosePanel;
    public delegate void ClosePanelHandler(object sender, EventArgs e);
    

    Then, in Form1's Button1_Click event (this raises the event):

     private void button1_Click(object sender, EventArgs e)
        {
         if (ClosePanel != null){
           ClosePanel(this, new EventArgs());
        }}
    

    -

    Finally, Form2 needs to handle the event (and be listening for it) in order to take action:

     private void HandleCloseRequest(object sender, EventArgs e)
        {
         panel1.Visible = false;
        }
    

    Also, modify

    private void button2_Click(object sender, EventArgs e)
        {
            Form1 Frm = new Form1();
            Frm.ClosePanel += HandleCloseRequest;
            Frm.Show();
        }
    

    I hope this helps a bit.