1

I need a way to refresh a form so that it executes all code in the constructor, I've tried with Form.Refresh(), this.Invalidate(), and even Form.Reload().. Still doesen't run as it does the first time I start the application, is there an easy way to do this?

1
  • Why can't you just create a new form entirely?
    – Servy
    Dec 19, 2012 at 17:25

1 Answer 1

12

The constructor can't be executed twice. You can build a workaround by putting your constructor's code in a method and calling it when it's needed.

Example:

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();
        DoStuff();
    }

    void DoStuff()
    {
        //Your code
    }

    void Button1_Click(object sender, EventArgs e)
    {
        DoStuff();
    }
}
3
  • 1
    That, alone, won't be the same as a fresh form. You'll also need to null out a lot of values that are never set at all in the constructor, you need to potentially wipe out information the user has entered into the form in some way, etc.
    – Servy
    Dec 19, 2012 at 17:30
  • Thanks, will definitely try this out. So the constructor doesen't even execute twice when I reload the form..?
    – jlodenius
    Dec 19, 2012 at 17:32
  • Servy is right. If you want a completely new Form it could be easier to just create a new one. @Jacco The constructor can be called only once in any type.
    – e_ne
    Dec 19, 2012 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.