Andy M Andy M - 3 months ago 20
C# Question

How to resize a button depending on its text

In the process of translating an application with C# + Winforms, I need to change a button's text depending on the language.

My problem is the following :

Let's say I want to translate a button from "Hi all!" to "Bonjour tout le monde" !

As you can guess, the button's size won't be the same if I enter english text or french one... My question is "simple", how can I manage to resize the button on the fly so the text fits its content in the button ?

So far I got something like that !

[Hi all!]

[Bonjour]

Answer

Your best bet is to set the AutoSize property as described ach's answer

However if AutoSize isn't working for you, resizing the button in code is easy enough. You can just need to set the button's width. The trick is making it big enough to fit your text.

   using(Graphics cg =  this.CreateGraphics())
   {
       SizeF size = cg.MeasureString("Please excuse my dear aunt sally",this.button1.Font);

       // size.Width+= 3; //add some padding .net v1.1 and 1.0 only
       this.button1.Padding = 3;
       this.button1.Width = (int)size.Width;

       this.button1.Text = "Please excuse my dear aunt sally";
   }
Comments