ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Resize To Text Width

Resizes width of a Windows control to the text that contains.

Source

/// <summary>
/// Resizes the control width to the content text
/// </summary>
/// <param name="control"></param>
/// <param name="text"></param>
/// <param name="font"></param>
/// <returns></returns>
public static void ResizeToTextWidth(this Control control)
{
    using (System.Drawing.Graphics g = control.CreateGraphics())
    {
        control.Width = (int)Math.Ceiling(g.MeasureString(control.Text, control.Font).Width);
    }
}

Example

private void AddLabel()
        {
                Label lbl= new Label();
                
                lbl.Name = "myName";
                lbl.Padding = new Padding(0);
                lbl.Margin = new Padding(0);
                lbl.TextAlign = ContentAlignment.MiddleCenter;
                lbl.Font = new Font(this.Font.FontFamily, 8, FontStyle.Bold);
                lbl.Text = "Some Random Text";

                lbl.ResizeToTextWidth();
                
                this.Controls.Add(lbl);
}

Author: Gabriel Espinoza

Submitted on: 15 jul. 2013

Language: C#

Type: System.Windows.Forms.Control

Views: 5184