user3563079
user3563079

Reputation: 23

How to save the state of a form?

I've built a Windows form application which contains some forms. I would like to create a button on a certain form which saves its state.

For example, if I have a textbox in which a user typed "Hello" and pressed the save button, when he goes back to this form, the textbox would still say "Hello". I want it to happen only in the same execution of the program, which means when the program closes and reopens, the textbox wouldn't say "Hello" anymore (which is why Settings don't fit my need I believe, because they keep the changes between executions).

Upvotes: 3

Views: 711

Answers (2)

Mani Muridi
Mani Muridi

Reputation: 410

Store your data in static variables and they will live until you close your program.

static string textboxText = textbox1.text;

Upvotes: 0

Cody Gray
Cody Gray

Reputation: 244903

Since you only want the form to retain its state while the application is running, the solution is very simple: never close the form, just hide it. When you're ready to display it again, show it. It will re-appear on the screen, everything exactly as it was left. (Unless, of course, you loop through the controls and reset their properties.)

In the simplest case, you accomplish this by substituting calls to this.Close with this.Hide. But it is likely more complicated than that, since the user can close your form with the big red X. To ensure all attempts to close the form are stealthily rerouted as requests to hide the form requires some minor finesse:

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        e.Cancel = true;  // cancel the request to close
        this.Hide();      // hide the form instead
    }
}

Note that this code checks the close reason and ensures that it's a user-initiated close request. This is very important. If you omit this part, you can't close the form programmatically, either!

Upvotes: 3

Related Questions