简体   繁体   中英

C# saving state of the form with all controls

I have a form and I have some buttons doing stuff.

When I press buttons the windows form controls, like textboxes or group-boxes, buttons appear and disappear and change place on my form, for it is a dynamic form:)

However, what I'd like to do is have a button ( BACK ) that will get my form to the state it was before an action of a button, putting back the controls in the place and state they were before action.

I thought of a C class MyState() that will have something like an array of Form1. I will be saving the form state in that array and when I'll press the back button to get from array that "copy" of the Form state and maybe an index for indexing states.

I have no idea how to implement this, unfortunately. :|

Can anyone show me the right way to do this?

class Mystate
{
    private Form1 [] state;

    public Mystate(int n)
    {
        this.state = new Form1[n];
    }

    public Form1 this[int index]
    {
        get
        {
            return state[index];
        }
        set
        {
            this.state[index] = value;
        }
    }
}

Sounds like you want an high level undo/redo feature for your forms.

Here is a framework for such things: http://www.codeproject.com/Articles/10576/An-Undo-Redo-Buffer-Framework

Here is an answer that is close but not exactly the same as your question (The pattern implimented is the same though): How to implement good and efficient undo/redo functionality for a TextBox

MementoPattern: http://www.codeproject.com/Articles/18025/Generic-Memento-Pattern-for-Undo-Redo-in-C

Nothing like this is built-in. You have to do this on your own.

I'd do it like this: First, define precisely what state you want to save. Example:

Control.Bounds
Control.Text
Checkbox.IsChecked
NumericUpDown.Value
...

Now we know exactly what needs to be saved.

Seconds, we need a way to create a snapshot of the current state of the form and recursively for all controls. You can implement this using reflection so that everything will be automatic no matter how many controls you have.

Third, you need to be able to apply a snapshot to an instance of Form. This is the opposite process of (2). This also can be done using reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM