Resize To Text Width

/// <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);
}

Description

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

Details

Double click on the code to select all.

 

;