0

In my winform there are some Splitter to separate some datagridviews, is there a way to store (and recover) the splitter position into the user.config?

I wish avoid to add a setting with a different name for each splitter if it's possible.

thanks in advance

ghiboz
  • 7,863
  • 21
  • 85
  • 131

2 Answers2

4

I came up with something you may be able to use. A few things about this example:

  • I used SplitContainer, but I'd imagine you could adapt this pretty easily.
  • I only scan the form's list of controls - this method won't pick up all SplitContainer (you'll probably need to do that recursively).
  • This assumes you have a user setting called SplitterPositions of type string.
  • This doesn't take into account future changes to the form (i.e. rearranging controls, adding new sections, removing existing sections, etc.), so it's a bit fragile in that regard.

I would personally recommend assigning names to your Splitters (or SplitContainers, depending on which type you're using) since that should shield you from the issues I mentioned.

In any event I hope this helps.

public Form1()
{
    InitializeComponent();

    Closing += Form1_Closing;

    ApplySavedSplitterData();
}

void Form1_Closing(object sender, CancelEventArgs e)
{
    SaveSplitterData();
}

private void SaveSplitterData()
{
    Settings.Default.SplitterPositions = string.Join(";", 
                     Controls.OfType<SplitContainer>()
                             .Select(s => s.SplitterDistance));

    Settings.Default.Save();
}

private void ApplySavedSplitterData()
{
    if (string.IsNullOrEmpty(Settings.Default.SplitterPositions))
    {
        return;
    }

    var positions = Settings.Default.SplitterPositions
                               .Split(';')
                               .Select(int.Parse).ToList();

    var splitContainers = Controls.OfType<SplitContainer>().ToList();

    for (var x = 0; x < positions.Count && x < splitContainers.Count; x++)
    {
        splitContainers[x].SplitterDistance = positions[x];
    }
}
Mark Carpenter
  • 17,445
  • 22
  • 96
  • 149
1

You can use the library from the article User Settings Applied to save the splitter position into the user settings.

Additionally you can persist the form size/location and any custom form setting.