Home > Mobile >  Dynamically resize TabControl and Form width to the number of TabPages
Dynamically resize TabControl and Form width to the number of TabPages

Time:09-21

I have a windows form with a TabControl and a ListView.
When I run the application, I want the Width of the TabControl to increase/decrease to show all the TabPages without horizontal scrollbar and have the Form resize it's Width accordingly, to insure that the TabControl and ListView are visible.

A screenshot is below.

enter image description here

CodePudding user response:

To auto-size a TabControl to the size of its Headers, you need to calculate the width of the text of each Header. It's simpler in case the Form TabControl AutoSize

Sample Project:
Starting form for this example

Starting out with that form, I'm going to add 8 tabs at run-time, calculate width of the text in the tabs padding size x2 (both sides of the tabs) and then resize controls as needed.

   public Form1()
    {
        InitializeComponent();
        //Clear our default tabs.
        tabControl1.TabPages.Clear();
        //Add more tabs than would be visible by default
        for (int i=1;i<=8;i  )
        {
            tabControl1.TabPages.Add("Tab "   i.ToString());
        }
        ResizeTabControl();
        ResizeListViewControl();
        ResizeForm();
    }
    void ResizeTabControl()
    {
        int tabCount = tabControl1.TabCount;

        float length = 0;
        using (Graphics g = CreateGraphics())
        {
            //Iterate through the tabs and get the length of the text.
            for (int i = 0; i <= tabCount - 1; i  )
                length  = g.MeasureString(tabControl1.TabPages[i].Text, tabControl1.Font).Width;
        }
        //Resize the tab control where X is the length of all text in the tabs plus padding x 2 x total tabs.
        tabControl1.Size = new Size(Convert.ToInt32(length)   (tabCount * 2 * tabControl1.Padding.X), tabControl1.Width);          
    }
    void ResizeListViewControl()
    {
        //Move listview 10 pixels away from tabcontrol's edge
        listView1.Location = new Point(tabControl1.Location.X   tabControl1.Width   10, listView1.Location.Y);
    }
    void ResizeForm()
    {
        //Resize form to accomodate changes.
        this.Width = listView1.Location.X   listView1.Width   20;
    }

After it's all said and done, this is what it looks like:

And with 20 tabs, because why not.

  • Related