C#: Close and Open two forms from a separate form

筅森魡賤 提交于 2019-12-24 17:18:48

问题


I have 3 forms. How can I make it so that one form is shown with .Show() and the other is hidden with .Hide() from a separate form?

This is part of my code

    private void buttonYes_Click(object sender, EventArgs e)
    {
        LoggedIn loggedinform = new LoggedIn();
        loggedinform.Hide(); // Hides another form that is in the background
        MainForm mainform = new MainForm();
        mainform.Show(); // Show first form
        this.Hide(); // Hides current form
    }

One problem, the LoggedIn form does not hide itself. From the looks of it it skips it and just goes for the mainform.Show();

Is this a bug or do I need to do something else?


回答1:


The line LoggedIn loggedinform = new LoggedIn() is going to create a new instance of that login window. That might be useful if, say, you intended to show 5 "Login" windows onscreen all at once. I think what you want to do is retrieve a reference to the login window that is already showing, and hide that; so, avoid creating a new one.

Properly passing references to existing objects around the program is kind of a structural problem, and one that I ran into quite a bit in my early programming days. The quick, unclean, and generally not-recommended way is to declare instances of those singular objects (like, maybe, your login window) as static, so they can be retrieved anywhere. However, to fully answer your question in the best way, maybe you could describe the structure of your program a bit more (full code isn't necessary, just generally-speaking, what the flow is between classes)




回答2:


Ok I figured it out. I can use

        Application.OpenForms[1].Hide();

[1] is the form I'm trying to hide. And it worked.

I also realized thanks to Katana that it makes sense why it wasn't working because it was basically making a new instance of the form instead of finding the current one. Sorry that my code is a mess.



来源:https://stackoverflow.com/questions/18196511/c-close-and-open-two-forms-from-a-separate-form

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