visual studio – C# Copy controls from one form to another programmatically


I have 2 forms for 2 different resolution displays. I need a way to select at run time the correct form for the current resolution. It does not change once the software is running.

Eg, I have a 1920×1080 layout and a 1280×800 layout. I created the mainform as the 1920×1080 display and a second form for the same controls and same names as the 1280×800 but adjust to fit the smaller resolution with different positions and font sizes.

The controls are all laid out in a Panel called mainPanel for each of the 2 forms. The component names are the same.

When I run the code and need to select the 1280×800, I remove and dispose of the mainPanel after also removing the events for the controls. I then add the second Form mainPanel to the existing form. This seems to work when I run the code as the smaller layout now appears but I cannot access the controls. It’s as if the originals are still there. The component names are the same and the original layout to suit the 1920×1080 is not visible, just the copy but I cannot attach events to the buttons or update any text boxes.

This is the code I use to dispose of the existing components and add the new ones. Event removal and adding not included.

        mainPanel.Controls.Clear();
        mainPanel.Dispose();
        //
        // Set the size of the window
        //
        Width = 1280;
        Height = 740;

        smallScreenForm = new SmallScreenForm();

        this.Controls.Add(smallScreenForm.mainPanel);

Leave a Reply

Your email address will not be published. Required fields are marked *