Home > Enterprise >  How to save and open the content in the one of subforms separately?
How to save and open the content in the one of subforms separately?

Time:10-25

There are two forms, a MainForm and a GraphicsForm. In MainForm, there are "New" and "Save", "Open" buttons. When clicking the "New", a GraphicsForm created (When the "New" is clicked multiple times, multiple GraphicsForms are created).

The question is, when created multiple GraphicsForms, and the user only wants to save the content in one of them or open a content file to one of them, How to implement this?

MainForm.cs

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private ToolStripMenuItem _winMenuItem = new ToolStripMenuItem();
    private GraphicsForm _graphicsForm;
    private int _counter = 1;
    private ContentDoc _contentDoc = new ContentDoc();

    private void New_Click(objec sender, EventArgs e)
    {
        _winMenuItem.Name = "Win";
        _winMenuItem.Text = "Windows";
        int item = MainMenuStrip.Items.IndexOf(_winMenuItem);
        if (item == -1)
        {
            MainMenuStrip.Items.Add(_winMenuItem);
            MainMenuStrip.MdiWindowListItem = _winMenuItem;
        }

        _graphicsForm = new GraphicsForm(_contentDoc);
        _graphicsForm.Name = string.Concat("Win_", _counter.ToString());
        _graphicsForm.Text = _graphicsForm.Name;
        _graphicsForm.MdiParent = this;
        _graphicsForm.Show();
        _graphicsForm.WindowState = FormWindowState.Maximized;
        _counter  ;
    }

    private void Save_Click(object sender, EventArgs e)
    {
        ... // here
    }

    private void Open_Click(object sender, EventArgs e)
    {
        ... // here
    }
}

GraphicsForm.cs

public partial class GraphicsForm : Form
{
    //ContentDoc is a class to manage all the graphics drawn by the user in the form.
    private ContentDoc _contentDoc = new ContentDoc();

    public GraphicsForm(ContentDoc contentDoc)
    {
        InitializeComponent();
        _contentDoc = contentDoc;
    }

    private Canvas_MouseDown()
    {
    }
    
    private Canvas_Paint()
    {
    }
    
    ...

CodePudding user response:

The parent form has an ActiveMdiChild property, so you can use the to access the currently-selected GraphicsForm instance:

var activeGraphicsForm = ActiveMdiChild as GraphicsForm;

There are other variations you might use, e.g. pattern matching, depending on the specific details and your preference.

You can then put your saving logic in a public method in GraphicsForm and call it from the parent form. Alternatively, you can put your saving logic in the parent form and expose the data to be saved via one or more public properties in GraphicsForm.

  • Related