简体   繁体   中英

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?

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.

Several ideas:

  • Keep the common controls outside the tabpanel;
  • Extend the TabPage/TabControl
  • Create a base UserControl with the common buttons and make usercontrols that inherit from it. Then place one inherited usercontrol per TabPage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM