> For the complete documentation index, see [llms.txt](https://docs-siticoneframework.gitbook.io/home/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-siticoneframework.gitbook.io/home/net-framework-or-net-core-ui/container-and-layout/siticone-splitcontainer/state-management.md).

# State Management

This feature allows the control's layout and settings to be saved and restored, ensuring a consistent user experience across sessions.

## Overview

The State Management feature of the SiticoneSplitContainer control enables the persistence of the control's configuration, including the splitter position, orientation, panel collapse states, lock state, and panel header visibility. Using properties such as `EnableStateManagement` and `SplitterPositionKey` along with methods for saving and loading state, developers can ensure that user customizations are retained between sessions, improving usability and consistency.

***

### Key Points

| Aspect                       | Description                                                                                                                                             |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| State Persistence            | Enables saving of the control's state (e.g., splitter position, orientation, panel collapse, lock state, header visibility) using the Windows Registry. |
| Import/Export Layout         | Provides methods (`ExportLayout()`, `ImportLayout(string json)`) for exporting and importing layout configurations in JSON format.                      |
| Automatic Saving and Loading | The control automatically saves state changes during user interactions and loads saved state when initialized.                                          |
| Custom Registry Key          | Developers can define a custom registry key via `SplitterPositionKey` to avoid conflicts and manage state storage.                                      |

***

### Best Practices

| Recommendation                    | Details                                                                                                                        |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Enable State Management Early     | Set `EnableStateManagement` to true during initialization to capture all relevant user interactions from the start.            |
| Use Custom Registry Keys          | Customize `SplitterPositionKey` for your application to ensure that multiple instances or different controls do not conflict.  |
| Combine with Layout Export/Import | Utilize the `ExportLayout()` and `ImportLayout(string json)` methods for backup, configuration sharing, or debugging purposes. |
| Validate State Data               | Implement error handling during state loading to fall back on default settings if the saved state is corrupted or invalid.     |

***

### Common Pitfalls

| Pitfall                           | Explanation                                                                                                 | Mitigation Strategy                                                                                  |
| --------------------------------- | ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| Unintended State Persistence      | Enabling state management without proper key management may lead to conflicts or unexpected layout changes. | Ensure each control instance uses a unique registry key and properly validates saved state data.     |
| Overwriting State Unintentionally | Frequent state saves during rapid user interactions might lead to overwriting preferred settings.           | Consider throttling state updates or confirming state changes before persisting them.                |
| Failing to Handle Exceptions      | Errors during state saving or loading (e.g., registry access issues) can cause runtime exceptions.          | Implement robust try-catch blocks to gracefully handle errors and revert to default state if needed. |

***

### Usage Scenarios

| Scenario                            | Description                                                                                            | Example Use Case                                                                                                  |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| Consistent UI Across Sessions       | Save and restore the splitter's position, panel visibility, and orientation between application runs.  | Retaining user-customized layout settings in a productivity application after the program is closed and reopened. |
| Layout Configuration Sharing        | Export the current layout to JSON for sharing with other users or for debugging purposes.              | Allowing administrators to pre-configure a standard layout and distribute it across the organization.             |
| Dynamic Adaptation of User Settings | Automatically apply saved settings when the control is loaded, ensuring a personalized user interface. | Restoring a complex panel configuration in a design tool where users adjust the interface frequently.             |

***

### Code Examples

#### 1. Enabling State Management

Below is an example of how to enable state management and set a custom registry key for state persistence:

```csharp
public class MyForm : Form
{
    private SiticoneSplitContainer splitContainer;

    public MyForm()
    {
        InitializeComponent();
        splitContainer = new SiticoneSplitContainer
        {
            Dock = DockStyle.Fill,
            // Enable saving and restoring state for this control
            EnableStateManagement = true,
            // Customize the registry key used for state management
            SplitterPositionKey = "MyApp_SplitterPosition"
        };

        this.Controls.Add(splitContainer);
    }
}
```

#### 2. Exporting and Importing Layout

This example demonstrates how to export the current layout configuration to JSON and then import it back into the control:

```csharp
public class LayoutManagementForm : Form
{
    private SiticoneSplitContainer splitContainer;
    private Button exportButton;
    private Button importButton;
    private TextBox layoutTextBox;

    public LayoutManagementForm()
    {
        InitializeComponent();
        splitContainer = new SiticoneSplitContainer
        {
            Dock = DockStyle.Fill,
            EnableStateManagement = true
        };

        exportButton = new Button
        {
            Text = "Export Layout",
            Dock = DockStyle.Top
        };

        importButton = new Button
        {
            Text = "Import Layout",
            Dock = DockStyle.Top
        };

        layoutTextBox = new TextBox
        {
            Dock = DockStyle.Bottom,
            Multiline = true,
            Height = 100
        };

        exportButton.Click += (sender, e) =>
        {
            string layoutJson = splitContainer.ExportLayout();
            layoutTextBox.Text = layoutJson;
        };

        importButton.Click += (sender, e) =>
        {
            string layoutJson = layoutTextBox.Text;
            try
            {
                splitContainer.ImportLayout(layoutJson);
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show($"Failed to import layout: {ex.Message}");
            }
        };

        this.Controls.Add(splitContainer);
        this.Controls.Add(exportButton);
        this.Controls.Add(importButton);
        this.Controls.Add(layoutTextBox);
    }
}
```

#### 3. Automatic State Loading on Parent Handle Creation

The control automatically loads state when added to a parent control. The following snippet illustrates that integration:

```csharp
public class AutoStateForm : Form
{
    private SiticoneSplitContainer splitContainer;

    public AutoStateForm()
    {
        InitializeComponent();
        splitContainer = new SiticoneSplitContainer
        {
            Dock = DockStyle.Fill,
            EnableStateManagement = true,
            SplitterPositionKey = "AutoStateForm_SplitterPosition"
        };

        // The control automatically loads its state on parent handle creation
        this.Controls.Add(splitContainer);
    }
}
```

***

### Review

| Aspect              | Details                                                                                                                                         |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| Ease of Integration | State management is straightforward to implement via property settings, requiring minimal additional code to persist user preferences.          |
| Robustness          | The control's built-in state saving and loading mechanisms ensure consistency across sessions, provided that proper error handling is in place. |
| Flexibility         | The ability to export/import layout configurations adds flexibility for backup, debugging, and standardized user experiences.                   |

***

### Summary

The State Management feature in the SiticoneSplitContainer control provides a robust framework for persisting the control's configuration across sessions. By saving settings such as splitter position, orientation, and panel visibility in the Windows Registry and offering layout export/import capabilities, developers can deliver a consistent and personalized user experience with minimal effort.

***

### Integration Steps

| Step   | Action                                                                                                                                           |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Step 1 | Instantiate the SiticoneSplitContainer and add it to your form, setting the Dock property appropriately.                                         |
| Step 2 | Enable state management by setting `EnableStateManagement` to true and assign a custom `SplitterPositionKey` if necessary.                       |
| Step 3 | Optionally subscribe to events or utilize methods like `ExportLayout()` and `ImportLayout(string json)` for additional configuration management. |
| Step 4 | Test state persistence by modifying the control layout, closing, and reopening the application to verify settings are retained.                  |

***

### Additional Resources

| Resource                   | Description                                                                                             | Example Link                                                     |
| -------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| .NET Registry Operations   | Documentation on working with the Windows Registry in .NET, crucial for understanding state management. | <https://docs.microsoft.com/dotnet/api/microsoft.win32.registry> |
| JSON Serialization in .NET | Guidance on using JSON for configuration storage, useful for export/import functionality.               | <https://docs.newtonsoft.com/json/help/html/SerializingJSON.htm> |

***

By following this comprehensive documentation and utilizing the provided code examples, developers can effectively implement and customize state management in the SiticoneSplitContainer control, ensuring a consistent and personalized user interface that persists across application sessions.
