Changing font size of label programatically

Jeffrey Schwartz 101 Reputation points
2021-09-02T22:04:00.64+00:00

I am using Visual C# with a WinForm project. I have a fixed-sized label to show some information. I want to be able to change the size of the font depending on the size (length) of the information (I'm trying to make sure all the information fits in the label).

The documentation I read says that I have to create a new font each time I want to change the font size with something life:

label1.Font = new Font(fontFamily, size);

I am concerned that since I will be changing the font size dozens of times, and therefore creating a new font many times, that I will be using up resources. Do I need to somehow dispose of the old font? How does one do that?

An alternative solution I am considering is two labels, one with a smaller font size, one with a larger font size, and programatically deciding which one should be visible and which one should be invisible. Is that a reasonable solution?

Thanks in advance for any advice.

Jeff Schwartz

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,821 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,199 questions
{count} votes

Accepted answer
  1. Sam of Simple Samples 5,516 Reputation points
    2021-09-03T04:49:16.627+00:00

    In your Form class, you can create multiple fonts only once that exist for the life of the application, as in:

    Font SmallFont = new Font("Arial", 8);
    Font MediumFont = new Font("Arial", 10);
    Font LargeFont = new Font("Arial", 12);
    

    Then set the label1.Font to whatever size you need.

    For example the following quick test works for me.

    public partial class Form1 : Form
    {
        Font SmallFont = new Font("Arial", 8);
        Font MediumFont = new Font("Arial", 10);
        Font LargeFont = new Font("Arial", 12);
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            label1.Font = SmallFont;
        }
    
        private void button2_Click(object sender, EventArgs e)
        {
            label1.Font = MediumFont;
        }
    
        private void button3_Click(object sender, EventArgs e)
        {
            label1.Font = LargeFont;
        }
    }
    

0 additional answers

Sort by: Most helpful