Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom TabPage control in C#

I'm building a small tabbed c# Form and I'd like each tab page to have some common features, notably, an OK button and an error message and to have a space for the specific form fields.

Has anyone else done something similar and how did you approach it?

like image 574
Tim Almond Avatar asked Mar 24 '10 15:03

Tim Almond


People also ask

How to create a Tab Control in c#?

To create a TabControl control at design-time, you simply drag and drop a TabControl control from Toolbox onto a Form in Visual Studio. After you drag and drop a TabControl on a Form, the TabControl1 is added to the Form and looks like Figure 1. A TabControl is just a container and has no value without tab pages.

How do I create a tab in Visual Studio?

Right-click on the tab control and select properties. You can see the tab page called "Collection Editor". To add an additional tab, please click the add button. To remove a tab, select it and click remove.


1 Answers

This is easy to do without extending either TabControl/TabPage.

Define one UserControl, and put the common elements on it you want on every TabPage.

On the Form: go ahead and design the TabPage specific controls you want for each TabPage : make sure they are not going to visually overlap with the common controls once the UserControl has been added.

In the Form Load Event of your main Form do something like this :

    // form scoped variable to hold a referece to the current UserControl
    private UserControl1 currentUserControl;

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach(TabPage theTabPage in tabControl1.TabPages)
        {
            currentUserControl = new UserControl1();

            theTabPage.Margin = new Padding(0);
            theTabPage.Padding = new Padding(0);

            theTabPage.Controls.Add(currentUserControl);

            currentUserControl.Location = new Point(0,0);

            currentUserControl.Dock = DockStyle.Fill;

            currentUserControl.SendToBack();
        }
    }

Even though the 'SendToBack isn't really required here it is "insurance" that your UserControl with the 'Okay button and TextBox for an error message are placed behind the individual controls you have assigned to each TabPage.

like image 166
BillW Avatar answered Sep 26 '22 17:09

BillW