How to modify a Form and refresh it from another Form

邮差的信 提交于 2019-12-11 16:23:35

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/11996273/how-to-modify-a-form-and-refresh-it-from-another-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!