Search code examples
c#winformsvisual-studio-2010tabcontrol

Moving controls on a form onto a tab


I have been working for months on a project in c# in Visual Studio 2010 (it interfaces with a camera, power supplies, and motion control). There is a form with many controls on it (radio buttons, buttons, text boxes, bitmap displays...). Now I would like to put all of that on a tab so i can have another tab. This is so that the second tab can have all the default settings on it (e.g, portnumber, baud rate, integration times, pathname...).

Is this doable? Is there a way to cut and paste or click and drag?

Update: I created a form, put a button on it that when clicked displays a message box with "Hello World". Then i added a tab control to the form, and dragged the button onto the first tab. The button still functions in the same way, displaying the message box when clicked.

So on my big form, i added a tabcontrol. Without resizing it, i did a select all, then unselected the tabcontrol, then dragged everything onto the tab. I then moved the tab control and resized it, then iteratively resized the tab window and moved all the controls. this worked, except the picturebox controls somehow got resized so they were larger than a screen width. Resized the pictureboxes and everything works. (perhaps i just needed the encouragement to give it a try...sorry if not the best question:).

To do this in code, in Form1.Designer.cs can add:

 this.tabPage1.Controls.Add(this.button1);

However, I would have to do this for every single control (about 200 of them in Designer.cs).


Solution

  • This can usually be done with some editing of the .Designer.cs file. First, make sure you make a backup in case it all goes horribly wrong. Place the tab control and add a single control (a button or anything) to it. Then examine the .Designer.cs file. As you point out yourself, you will see a line like this:

    this.tabPage1.Controls.Add(this.button1);
    

    As for the existing controls on the form, there will be a bunch of lines like this:

     this.Controls.Add(this.meErrorReport);
     this.Controls.Add(this.peWarningSign);
     this.Controls.Add(this.meHeaderText);
     this.Controls.Add(this.btnClose);
    

    So what you do is to cut these lines (not including the one for the tab control!), and paste them just following the line shown above, and do a find-and-replace to change them so they match the first one:

     this.tabPage1.Controls.Add(this.meErrorReport);
     this.tabPage1.Controls.Add(this.peWarningSign);
     this.tabPage1.Controls.Add(this.meHeaderText);
     this.tabPage1.Controls.Add(this.btnClose);
    

    This should usually do the trick. The controls may be positioned wrong, and most will be hidden until you increase the size of the tab control, but these are minor problems that can be fixed.

    PS. I know you've already fixed your problem, but I'm posting this answer in case it can help you, or someone else, in the future.