How to resize a button depending on its text

To enable a Button in WinForms grow and/or shrink depending on the size of the Text, you need to set the button's AutoSize property to True and the AutoSizeMode property to GrowAndShrink.

// C#
btn.AutoSize = true;
btn.AutoSizeMode = AutoSizeMode.GrowAndShrink;

' VB.NET
btn.AutoSize = True
btn.AutoSizeMode = AutoSizeMode.GrowAndShrink

Please note that the AutoSize property will only allow the button's size to grow if the AutoSizeMode property is set to GrowOnly; by changing the AutoSizeMode property to GrowAndShrink, the button will now automatically extend or reduce in width and height based on its Text property.

Also note that in setting the two properties as shown above, you can make use of new lines (Environment.NewLine or vbCrLf) in the Text property and the button will scale down as needed.


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";
   }

Try this:

Button.AutoSize = true;
Button.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly;
Button.TextAlign = ContentAlignment.MiddleLeft;
Button.Padding = new Padding(0, 0, 0, 0);

There's absolutely no need to use the underlying Graphics object as the other posters have said.

If you set the button's AutoSize property to true, the AutoSizeMode to GrowAndShrink, and the AutoEllipsis to false, it will resize automatically to fit the text.

That being said, you may need to make several layout adjustments to make this change fit into your UI. You can adjust the button's padding to add space around the text, and you may want to place your buttons in a TableLayoutPanel (or something) to stop them from overlapping when they resize.

Edit: @mastro pointed out that: AutoEllipsis is only valid when AutoSize is false (As explained in the documentation), so it can be safely ignored as long as the other three properties are set correctly.