Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C#

Create Your Own TabControl In C#

Rate me:
Please Sign up or sign in to vote.
4.39/5 (15 votes)
9 Mar 2018CPOL3 min read 29.6K   3.2K   20   3
In this article, we will create a simple TabControl using only Buttons and Panels in C#.

Image 1

Image 2

Let's create our own simple TabControl using Buttons & Panels. Create a C# Windows Forms Application project in Visual Studio. I named it MyTabControl. I used simple customized buttons but you can create your own.

                     http://customcontrolsincs.blogspot.in/

Using the Code

Step 1

Go to Project -> Add Class & enter name ButtonX and copy/paste the following code. Well, you know we need a button as a tab, but whenever click action is performed on that button, its back color must not change, but remaining buttons must change whenever mouse enters or leaves.

In the following code, this action is controlled using isChanged boolean variable. Change the following code as you want to customize it.

C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace MyTabControl
{
    public class ButtonX : System.Windows.Forms.Button
    {
        Color clr1;
        private Color color = Color.Teal;
        private Color m_hovercolor = Color.FromArgb(0, 0, 140);
        private Color clickcolor = Color.FromArgb(160, 180, 200);
        private int textX = 6;
        private int textY = -20;
        private String text = "_";
        private bool isChanged = true;

        public String DisplayText
        {
            get { return text; }
            set { text = value; Invalidate(); }
        }
        public Color BXBackColor
        {
            get { return color; }
            set { color = value; Invalidate(); }
        }

        public Color MouseHoverColor
        {
            get { return m_hovercolor; }
            set { m_hovercolor = value; Invalidate(); }
        }

        public Color MouseClickColor1
        {
            get { return clickcolor; }
            set { clickcolor = value; Invalidate(); }
        }

        public bool ChangeColorMouseHC
        {
            get { return isChanged; }
            set { isChanged = value; Invalidate(); }
        }


        public int TextLocation_X
        {
            get { return textX; }
            set { textX = value; Invalidate(); }
        }
        public int TextLocation_Y
        {
            get { return textY; }
            set { textY = value; Invalidate(); }
        }
        public ButtonX()
        {
            this.Size = new System.Drawing.Size(31, 24);
            this.ForeColor = Color.White;
            this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.Text = "_";
            text = this.Text;
        }

        //method mouse enter
        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            clr1 = color;
            color = m_hovercolor;
        }

        //method mouse leave
        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            if (isChanged)
            {
                color = clr1;
            }
        }

        protected override void OnMouseDown(MouseEventArgs mevent)
        {
            base.OnMouseDown(mevent);
            if (isChanged)
            {
                color = clickcolor;
            }
        }

        protected override void OnMouseUp(MouseEventArgs mevent)
        {
            base.OnMouseUp(mevent);
            if (isChanged)
            {
                color = clr1;
            }
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
            text = this.Text;
            if (textX == 100 && textY == 25)
            {
                textX = ((this.Width) / 3) + 10;
                textY = (this.Height / 2) - 1;
            }

            Point p = new Point(textX, textY);
            pe.Graphics.FillRectangle(new SolidBrush(color), ClientRectangle);
            pe.Graphics.DrawString(text, this.Font, new SolidBrush(this.ForeColor), p);
        }
    }
}

Step 2

Go to Project -> Add User Control & enter name TabControlX. Give whatever back color to it and the components which we are going to add on it. 

Step 3

  • Add Panel on TabControlX, give it a BackTopPanel name, set Dock property to Top and Height to 40.
  • Add Panel on BackTopPanel, give it a RibbonPanel name, set Dock property to Bottom and Height to 2.
  • Add Panel on BackTopPanel, give it a TabButtonPanel name, Anchor to Left-Top-Right, set Location to (0,0) and specific Width leaving some extra portion of BackTopPanel at end and Height to 30.
  • Add ToolStrip on BackTopPanel, Set Dock property to None, Anchor to Top-Right, add DropDownButton from added ToolStrip and add DropDownOpening event to it.
  • Add Panel on TabControlX, give it a TabPanel name, set Dock property to Fill.

Step 4

Go to Project -> Add User Control & enter name TabPanelControl. TabPanelControl is used to hold the components that we want to add to tabs. Download the source code.

Step 5

Now we need to create a list of buttons that represent tabs and a list of added components (TabPanelControl).

C#
int selected_index = -1;
public List<ButtonX> buttonlist = new List<ButtonX> { };
public List<TabPanelControl> tabPanelCtrlList = new List<TabPanelControl> { };

void UpdateButtons()
{
    if (buttonlist.Count > 0)
    {
        for (int i = 0; i < buttonlist.Count; i++)
        {
            if (i == selected_index)
            {
                buttonlist[i].ChangeColorMouseHC = false;
                buttonlist[i].BXBackColor = Color.FromArgb(20, 120, 240);
                buttonlist[i].ForeColor = Color.White;
                buttonlist[i].MouseHoverColor = Color.FromArgb(20, 120, 240);
                buttonlist[i].MouseClickColor1 = Color.FromArgb(20, 120, 240);
            }
            else
            {
                buttonlist[i].ChangeColorMouseHC = true;
                buttonlist[i].ForeColor = Color.White;
                buttonlist[i].MouseHoverColor = Color.FromArgb(20, 120, 240);
                buttonlist[i].BXBackColor = Color.FromArgb(40, 40, 40);
                buttonlist[i].MouseClickColor1 = Color.FromArgb(20, 80, 200);
            }
        }
    }
}

void createAndAddButton(string tabtext, TabPanelControl tpcontrol, Point loc)
{
    ButtonX bx = new ButtonX();
    bx.DisplayText = tabtext;
    bx.Text = tabtext;
    bx.Size = new Size(130, 30);
    bx.Location = loc;
    bx.ForeColor = Color.White;
    bx.BXBackColor = Color.FromArgb(20, 120, 240);
    bx.MouseHoverColor = Color.FromArgb(20, 120, 240);
    bx.MouseClickColor1 = Color.FromArgb(20, 80, 200);
    bx.ChangeColorMouseHC = false;
    bx.TextLocation_X = 10;
    bx.TextLocation_Y = 9;
    bx.Font = this.Font;
    bx.Click += button_Click;
    TabButtonPanel.Controls.Add(bx);
    buttonlist.Add(bx);
    selected_index++;

    tabPanelCtrlList.Add(tpcontrol);
    TabPanel.Controls.Clear();
    TabPanel.Controls.Add(tpcontrol);

    UpdateButtons();
}

void button_Click(object sender, EventArgs e)
{
    string btext = ((ButtonX)sender).Text;
    int index = 0, i;
    for (i = 0; i < buttonlist.Count; i++)
    {
        if (buttonlist[i].Text == btext)
        {
            index = i;
        }
    }
    TabPanel.Controls.Clear();
    TabPanel.Controls.Add(tabPanelCtrlList[index]);
    selected_index = ((ButtonX)sender).TabIndex;

    UpdateButtons();
}

public void AddTab(string tabtext, TabPanelControl tpcontrol)
{
    if (!buttonlist.Any())
    {
        createAndAddButton(tabtext, tpcontrol, new Point(0, 0));
    }
    else
    {
        createAndAddButton(tabtext, tpcontrol,
        new Point(buttonlist[buttonlist.Count - 1].Size.Width +
        buttonlist[buttonlist.Count - 1].Location.X, 0));
    }
}
UpdateButtons() function just changes the color properties of buttons but the selected index. createAndAddButton() function create a new object of class ButtonX, sets properties to it. Also adds an object of TabPanelControl to the TabPanel.

In button_Click function event, clears the controls of TabPanel and adds the control from tabPanelCtrlList of selected index. AddTab() is the function which we will call to add a tab on tabcontrol.

C#
private void toolStripButton1_DropDownOpening(object sender, EventArgs e)
{
    toolStripDropDownButton1.DropDownItems.Clear();
    int mergeindex = 0;
    for (int i = 0; i < buttonlist.Count; i++)
    {
        ToolStripMenuItem tbr = new ToolStripMenuItem();
        tbr.Text = buttonlist[i].Text;
        tbr.MergeIndex = mergeindex;
        if (selected_index == i)
        {
            tbr.Checked = true;
        }
        tbr.Click += tbr_Click;
        toolStripDropDownButton1.DropDownItems.Add(tbr);
        mergeindex++;
    }
}

List<string> btstrlist = new List<string> { };
void BackToFront_SelButton()
{
    int i = 0;

    TabButtonPanel.Controls.Clear();
    btstrlist.Clear();
    for (i = 0; i < buttonlist.Count; i++)
    {
        btstrlist.Add(buttonlist[i].Text);
    }

    buttonlist.Clear();

    for (int j = 0; j < btstrlist.Count; j++)
    {
        if (j == 0)
        {
            ButtonX bx = new ButtonX();
            bx.DisplayText = btstrlist[j];
            bx.Text = btstrlist[j];
            bx.Size = new Size(130, 30);
            bx.Location = new Point(0,0);
            bx.ForeColor = Color.White;
            bx.BXBackColor = Color.FromArgb(20, 120, 240);
            bx.MouseHoverColor = Color.FromArgb(20, 120, 240);
            bx.MouseClickColor1 = Color.FromArgb(20, 80, 200);
            bx.ChangeColorMouseHC = false;
            bx.TextLocation_X = 10;
            bx.TextLocation_Y = 9;
            bx.Font = this.Font;
            bx.Click += button_Click;
            TabButtonPanel.Controls.Add(bx);
            buttonlist.Add(bx);
            selected_index++;
        }
        else if (j > 0)
        {
            ButtonX bx = new ButtonX();
            bx.DisplayText = btstrlist[j];
            bx.Text = btstrlist[j];
            bx.Size = new Size(130, 30);
            bx.ForeColor = Color.White;
            bx.BXBackColor = Color.FromArgb(20, 120, 240);
            bx.MouseHoverColor = Color.FromArgb(20, 120, 240);
            bx.MouseClickColor1 = Color.FromArgb(20, 80, 200);
            bx.ChangeColorMouseHC = false;
            bx.TextLocation_X = 10;
            bx.TextLocation_Y = 9;
            bx.Font = this.Font;
            bx.Click += button_Click;
            bx.Location = new Point(buttonlist[j - 1].Size.Width +
                          buttonlist[j - 1].Location.X, 0);
            TabButtonPanel.Controls.Add(bx);
            buttonlist.Add(bx);
            selected_index++;
        }
    }
    TabPanel.Controls.Clear();
}

void tbr_Click(object sender, EventArgs e)
{
    int i;
    for (int k = 0; k < ((ToolStripMenuItem)sender).MergeIndex; k++)
    {
        int j = 0;
        for (i = ((ToolStripMenuItem)sender).MergeIndex; i >= 0; i--)
        {
            ButtonX but = buttonlist[i];
            ButtonX temp = buttonlist[j];
            buttonlist[i] = temp;
            buttonlist[j] = but;

            TabPanelControl uct1 = tabPanelCtrlList[i];
            TabPanelControl tempusr = tabPanelCtrlList[j];
            tabPanelCtrlList[i] = tempusr;
            tabPanelCtrlList[j] = uct1;
        }
    }

    string btext = ((ToolStripMenuItem)sender).Text;
    BackToFront_SelButton();
    selected_index = 0;
    TabPanel.Controls.Add(tabPanelCtrlList[buttonlist[0].TabIndex]);
    UpdateButtons();
}

public void RemoveTab(int index)
{
    if (index >= 0 && buttonlist.Count > 0 && index < buttonlist.Count)
    {
        buttonlist.RemoveAt(index);
        tabPanelCtrlList.RemoveAt(index);
        BackToFront_SelButton();
        if (buttonlist.Count > 1)
        {
            if (index - 1 >= 0)
            {
                TabPanel.Controls.Add(tabPanelCtrlList[index - 1]);
            }
            else
            {
                TabPanel.Controls.Add(tabPanelCtrlList[(index - 1) + 1]);
                selected_index = (index - 1) + 1;
            }
        }
        selected_index = index - 1;

        if (buttonlist.Count == 1)
        {
            TabPanel.Controls.Add(tabPanelCtrlList[0]);
            selected_index = 0;
        }
    }
    UpdateButtons();
}

BackToFront_SelButton() brings the tab which is out of screen. First, it copies all buttons text to btstrlist, clears the buttonlist, creates a new object and adds each item again to buttonlist.

tbr_Click() function swaps the items from buttonlist and tabPanelCtrlList till the count of buttonlist. RemoveTab() function removes the entry of item from buttonlist and tabPanelCtrlList

Step 6

  • Now debug your project.
  • Drag & Drop TabControlX onto Form.
  • You can use properties to access colors.
  • Download the source code.
  • To just add tab, call function AddTab().
C#
tabControlX1.AddTab("TabPage 1", null);

To add component to tabpage, first create an object of TabPanelControl, and add all controls on TabPanelControl object and then pass it as a parameter to AddTab() function and to remove a tab, call RemoveTab(int index) function by passing the index of the tab that wants to remove.

C#
int cnt = 1;
private void button1_Click(object sender, EventArgs e)
{
    tabControlX1.AddTab("Tab "+cnt, null);
    cnt++;
}

private void button2_Click(object sender, EventArgs e)
{
    TabPanelControl tpc = new TabPanelControl();
    tpc.Dock = DockStyle.Fill;
    RichTextBox rtb = new RichTextBox();
    rtb.Dock = DockStyle.Fill;
    tpc.Controls.Add(rtb);
    tabControlX1.AddTab("Tab " + cnt, tpc);
    cnt++;
}

That's it!

Download the source code to view the tabcontrol source code also a little bit Notepad implementation using our created tabcontrol. Here's the output of the above procedure.

Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Software Engineer

Comments and Discussions

 
Generala lot of redundant code Pin
sx200812-Mar-18 8:54
sx200812-Mar-18 8:54 
There's a lot of redundant code.
Here an example:
C#
void BackToFront_SelButton()
        {
            int i = 0;
            TabButtonPanel.Controls.Clear();
            btstrlist.Clear();
            for (i = 0; i < buttonlist.Count; i++)
            {
                btstrlist.Add(buttonlist[i].Text);
            }

            buttonlist.Clear();

            for (int j = 0; j < btstrlist.Count; j++)
            {
                if (j == 0)
                {
                    ButtonX bx = new ButtonX();
                    bx.DisplayText = btstrlist[j];
                    bx.Text = btstrlist[j];
                    bx.Size = new Size(130, 30);
                    bx.Location = new Point(0,0);
                    bx.ForeColor = Color.White;
                    bx.BXBackColor = Color.FromArgb(20, 120, 240);
                    bx.MouseHoverColor = Color.FromArgb(20, 120, 240);
                    bx.MouseClickColor1 = Color.FromArgb(20, 80, 200);
                    bx.ChangeColorMouseHC = false;
                    bx.TextLocation_X = 10;
                    bx.TextLocation_Y = 9;
                    bx.Font = this.Font;
                    bx.Click += button_Click;
                    TabButtonPanel.Controls.Add(bx);
                    buttonlist.Add(bx);
                    selected_index++;
                }
                else if (j > 0)
                {
                    ButtonX bx = new ButtonX();
                    bx.DisplayText = btstrlist[j];
                    bx.Text = btstrlist[j];
                    bx.Size = new Size(130, 30);
                    bx.ForeColor = Color.White;
                    bx.BXBackColor = Color.FromArgb(20, 120, 240);
                    bx.MouseHoverColor = Color.FromArgb(20, 120, 240);
                    bx.MouseClickColor1 = Color.FromArgb(20, 80, 200);
                    bx.ChangeColorMouseHC = false;
                    bx.TextLocation_X = 10;
                    bx.TextLocation_Y = 9;
                    bx.Font = this.Font;
                    bx.Click += button_Click;
                    bx.Location = new Point(buttonlist[j - 1].Size.Width + buttonlist[j - 1].Location.X, 0);
                    TabButtonPanel.Controls.Add(bx);
                    buttonlist.Add(bx);
                    selected_index++;
                }
            }
            TabPanel.Controls.Clear();
        }
After some refacturation:
C#
void BackToFront_SelButton()
        {
            TabButtonPanel.Controls.Clear();
            btstrlist.Clear();
            foreach(var btn in buttonlist)
            {
                btstrlist.Add(btn.Text);
            }
            buttonlist.Clear();
            for (int j = 0; j < btstrlist.Count; j++)
            {

                ButtonX bx = new ButtonX();
                bx.DisplayText = btstrlist[j];
                bx.Text = btstrlist[j];
                bx.Size = new Size(130, 30);
                bx.ForeColor = Color.White;
                bx.BXBackColor = Color.FromArgb(20, 120, 240);
                bx.MouseHoverColor = Color.FromArgb(20, 120, 240);
                bx.MouseClickColor1 = Color.FromArgb(20, 80, 200);
                bx.ChangeColorMouseHC = false;
                bx.TextLocation_X = 10;
                bx.TextLocation_Y = 9;
                bx.Font = this.Font;
                bx.Click += button_Click;
                bx.Location = new Point(0,0);
                if (j > 0)
                {
                    bx.Location = new Point(buttonlist[j - 1].Size.Width + buttonlist[j - 1].Location.X, 0);
                }
                TabButtonPanel.Controls.Add(bx);
                buttonlist.Add(bx);
                selected_index++;
            }
            TabPanel.Controls.Clear();
        }
This is only one example of the weakness of the code.
I'm sorry but it's not ready for use in a project.
PraiseNice Pin
RickZeeland9-Mar-18 21:19
mveRickZeeland9-Mar-18 21:19 
GeneralRe: Nice Pin
Pritam Zope10-Mar-18 4:31
Pritam Zope10-Mar-18 4:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.