Click here to Skip to main content
12,063,909 members (65,000 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

23.6K views
2K downloads
26 bookmarked
Posted

C# Resize ALL Controls at Runtime

, 26 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Simple and easy to use code in resizing all controls

Introduction

This is my second post which tackles auto form resizing. My previous tip can be found here. I am fascinated with how the controls resize themselves to their containers at runtime. Though it is easy to imagine, sometimes the question which some programmer would ask is "Where do I start?".

Background

In the program, I use the IEnumerable Interface and place it inside a class so it can be accessible to every form. You just reference the exact class name. Feel free to comment.

Using the Code

This is the default namespace of C#. Since this is C#, you should add this to import statement using System.Collections; in a class so you can use the array collection. Just create a new form. Copy this code below. The class is included in the attached file.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; 

The collections are a good way to keep track of objects that your application might need to dynamically create and destroy at runtime. You can store or add an item of any data type. A friendly reminder, don't forget to include the System.Collections.Generic namespace in case you miss it to safeguard against inappropriate data types being added in the collection. You can create your own variable name if you want as long as it is understandable. Inside your MainForm, i.e. Form1:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        clsResize _form_resize;

        public Form1()
        {
            InitializeComponent();

           _form_resize = new clsResize(this); //I put this after the initialize event to be sure that all controls are initialized properly

           this.Load += new EventHandler(_Load); //This will be called after the initialization // form_load
           this.Resize += new EventHandler(_Resize); //form_resize
        } 

Below is the form load event. At this point, initial values are stored in the collection for later calculations. This will store all values into ArrayList inside the class.

private void _Load(object sender, EventArgs e)
       {
           _form_resize._get_initial_size();
       }

Below is the resize event, This will call the _resize event inside the class for later calculations.

        private void _Resize(object sender, EventArgs e)
        {
            _form_resize._resize();
        }
    }
}  

Inside the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms; 

This is private declaration inside the class, no other static definition has been included for safety purposes.

List<System.Drawing.Rectangle> _arr_control_storage = new List<System.Drawing.Rectangle>();
    private bool showRowHeader = false;
    public clsResize(Form _form_)
    {
        form = _form_; //the calling form
        _formSize = _form_.ClientSize; //Save initial form size
        _fontsize = _form_.Font.Size; //Font size
    }

    private float _fontsize  { get; set; }

    private System.Drawing.SizeF _formSize {get;set; }

    private Form form { get; set; } 

This event gets / records the initial size and location of the controls inside the form:

public void _get_initial_size() //get initial size//
    {
        var _controls = _get_all_controls(form);//call the enumerator
        foreach (Control control in _controls) //Loop through the controls
        {
            _arr_control_storage.Add(control.Bounds); //saves control bounds/dimension            
            //If you have datagridview
            if (control.GetType() == typeof(DataGridView))
                _dgv_Column_Adjust(((DataGridView)control), showRowHeader);
        }
    } 

This event sets the control size based on the ratio of adjustment. As you can see, I removed the condition with this kind of statement: (if current_form size < initial_form size), then return to initial size. Using the code below, the control resizes itself to its container if the current form size is less than the initial form size.

public void _resize() //Set the resize
    {
        double _form_ratio_width = (double)form.ClientSize.Width /(double)_formSize.Width; //ratio could be greater or less than 1
        double _form_ratio_height = (double)form.ClientSize.Height / (double)_formSize.Height; // this one too
        var _controls = _get_all_controls(form); //reenumerate the control collection
        int _pos = -1;//do not change this value unless you know what you are doing
        foreach (Control control in _controls)
        {
            // do some math calc
            _pos += 1;//increment by 1;
            System.Drawing.Size _controlSize = new System.Drawing.Size
            ((int)(_arr_control_storage[_pos].Width * _form_ratio_width),
                (int)(_arr_control_storage[_pos].Height * _form_ratio_height)); //use for sizing

            System.Drawing.Point _controlposition = new System.Drawing.Point((int)
            (_arr_control_storage[_pos].X * _form_ratio_width),
            (int) (_arr_control_storage[_pos].Y * _form_ratio_height));//use for location

            //set bounds
            control.Bounds = new System.Drawing.Rectangle(_controlposition, _controlSize); //Put together

            //Assuming you have a datagridview inside a form()
            //if you want to show the row header, replace the false statement of 
            //showRowHeader on top/public declaration to true;
            if (control.GetType() == typeof(DataGridView))
                _dgv_Column_Adjust(((DataGridView)control), showRowHeader);


            //Font AutoSize
            control.Font = new System.Drawing.Font(form.Font.FontFamily,
             (float)(((Convert.ToDouble(_fontsize) * _form_ratio_width) / 2) +
              ((Convert.ToDouble(_fontsize) * _form_ratio_height) / 2)));

        }
    }

I included this one if you have a datagridview and you want to resize the column base on its container.

private void _dgv_Column_Adjust(DataGridView dgv, bool _showRowHeader) //if you have Datagridview
//and want to resize the column base on its dimension.
{
    int intRowHeader = 0;
    const int Hscrollbarwidth = 5;
    if (_showRowHeader)
        intRowHeader = dgv.RowHeadersWidth;
    else
        dgv.RowHeadersVisible = false;

    for (int i = 0; i < dgv.ColumnCount; i++)
    {
        if (dgv.Dock == DockStyle.Fill) //in case the datagridview is docked
            dgv.Columns[i].Width = ((dgv.Width - intRowHeader) / dgv.ColumnCount);
        else
            dgv.Columns[i].Width = ((dgv.Width - intRowHeader - Hscrollbarwidth) / dgv.ColumnCount);
    }
}

In the attached project, I have added a sample program with complete code for reference purposes.

Points of Interest

The code is easy to understand. Enjoy!

History

  • March 27, 2014 - First post
  • April 06, 2014 - Revised code (Resized the control even if the current form size is less than the initial)

License

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

Share

About the Author

emerR46
Engineer
Philippines Philippines
A tech hobbyist and loves computer programming. When I design, I focused on the responsiveness GUI and at the same time in the performance(especially speedy network connectivity for DB). In my free time, I usually do android programming/ c# GUI coding.


Java/.Net



-emer-

You may also be interested in...

Comments and Discussions

 
QuestionSuggestion Pin
Member 1207484923-Nov-15 8:14
memberMember 1207484923-Nov-15 8:14 
QuestionERROR Pin
MAYANK GEETE18-Nov-15 0:55
professionalMAYANK GEETE18-Nov-15 0:55 
QuestionExcellent job! Very helpful! Pin
www.kkk8-Jun-15 12:48
memberwww.kkk8-Jun-15 12:48 
AnswerRe: Excellent job! Very helpful! Pin
emerR4616-Jun-15 12:19
memberemerR4616-Jun-15 12:19 
QuestionThe Label Control doesn't seem to resize Pin
Harry Whitehouse21-Apr-15 21:13
memberHarry Whitehouse21-Apr-15 21:13 
AnswerRe: The Label Control doesn't seem to resize Pin
emerR4616-Jun-15 12:21
memberemerR4616-Jun-15 12:21 
GeneralRe: The Label Control doesn't seem to resize Pin
Member 1173601531-Aug-15 15:46
memberMember 1173601531-Aug-15 15:46 
GeneralRe: The Label Control doesn't seem to resize Pin
Member 1173601531-Aug-15 15:50
memberMember 1173601531-Aug-15 15:50 
QuestionDon't see results in columns Pin
Member 1096246522-Jul-14 0:35
memberMember 1096246522-Jul-14 0:35 
AnswerRe: Don't see results in columns Pin
kix4622-Jul-14 16:04
memberkix4622-Jul-14 16:04 
QuestionShowing form in panel Pin
Member 91175778-Apr-14 18:57
memberMember 91175778-Apr-14 18:57 
AnswerRe: Showing form in panel Pin
kix469-Apr-14 6:03
memberkix469-Apr-14 6:03 
GeneralRe: Showing form in panel Pin
Member 91175779-Apr-14 17:56
memberMember 91175779-Apr-14 17:56 
GeneralRe: Showing form in panel Pin
Member 91175779-Apr-14 20:00
memberMember 91175779-Apr-14 20:00 
GeneralRe: Showing form in panel Pin
kix469-Apr-14 20:23
memberkix469-Apr-14 20:23 
GeneralRe: Showing form in panel Pin
Member 91175779-Apr-14 21:24
memberMember 91175779-Apr-14 21:24 
GeneralRe: Showing form in panel Pin
kix469-Apr-14 22:22
memberkix469-Apr-14 22:22 
GeneralRe: Showing form in panel Pin
Member 911757710-Apr-14 0:39
memberMember 911757710-Apr-14 0:39 
GeneralRe: Showing form in panel Pin
kix4610-Apr-14 2:06
memberkix4610-Apr-14 2:06 
GeneralRe: Showing form in panel Pin
Member 911757710-Apr-14 5:06
memberMember 911757710-Apr-14 5:06 
QuestionException Pin
Member 91175778-Apr-14 0:32
memberMember 91175778-Apr-14 0:32 
AnswerRe: Exception Pin
kix468-Apr-14 17:06
memberkix468-Apr-14 17:06 
GeneralRe: Exception Pin
Member 91175778-Apr-14 18:58
memberMember 91175778-Apr-14 18:58 
QuestionSample file Pin
Member 91175776-Apr-14 19:07
memberMember 91175776-Apr-14 19:07 
QuestionRe Comment of John Bret Pin
Member 91175776-Apr-14 1:38
memberMember 91175776-Apr-14 1:38 
AnswerRe: Re Comment of John Bret Pin
kix466-Apr-14 6:47
memberkix466-Apr-14 6:47 
AnswerRe: Re Comment of John Bret Pin
CHill606-Apr-14 7:06
protectorCHill606-Apr-14 7:06 
GeneralRe: Re Comment of John Bret Pin
kix466-Apr-14 13:15
memberkix466-Apr-14 13:15 
GeneralRe: Re Comment of John Bret Pin
Member 91175776-Apr-14 17:25
memberMember 91175776-Apr-14 17:25 
GeneralRe: Re Comment of John Bret Pin
Ben Sycha22-Apr-14 6:58
memberBen Sycha22-Apr-14 6:58 
GeneralNot such a good approach Pin
John Brett28-Mar-14 7:29
memberJohn Brett28-Mar-14 7:29 
AnswerRe: Not such a good approach Pin
kix4628-Mar-14 13:52
memberkix4628-Mar-14 13:52 
GeneralRe: Not such a good approach Pin
John Brett29-Mar-14 21:48
memberJohn Brett29-Mar-14 21:48 
GeneralRe: Not such a good approach Pin
kix4630-Mar-14 1:20
memberkix4630-Mar-14 1:20 
GeneralRe: Not such a good approach Pin
John Brett30-Mar-14 22:01
memberJohn Brett30-Mar-14 22:01 
SuggestionWhen I drag the form smaller than it default size,It flushed all the time Pin
fuapolloqi28-Mar-14 0:29
memberfuapolloqi28-Mar-14 0:29 
AnswerRe: When I drag the form smaller than it default size,It flushed all the time Pin
kix4628-Mar-14 2:38
memberkix4628-Mar-14 2:38 
GeneralRe: When I drag the form smaller than it default size,It flushed all the time Pin
fuapolloqi30-Mar-14 18:51
memberfuapolloqi30-Mar-14 18:51 
GeneralRe: When I drag the form smaller than it default size,It flushed all the time Pin
kix466-Apr-14 15:30
memberkix466-Apr-14 15:30 
QuestionWhat is the advantage of your approach? Pin
Klaus Luedenscheidt27-Mar-14 20:44
memberKlaus Luedenscheidt27-Mar-14 20:44 
AnswerRe: What is the advantage of your approach? Pin
kix4627-Mar-14 22:50
memberkix4627-Mar-14 22:50 
GeneralRe: What is the advantage of your approach? Pin
Member 1054236229-Mar-14 6:22
memberMember 1054236229-Mar-14 6:22 
Questionthank you. Pin
wangfnso27-Mar-14 1:18
memberwangfnso27-Mar-14 1:18 
AnswerRe: thank you. Pin
kix4627-Mar-14 2:21
memberkix4627-Mar-14 2:21 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160204.4 | Last Updated 27 Mar 2014
Article Copyright 2014 by emerR46
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid