Search code examples
c#winformslabeltext-alignment

Update text in WinForms Label symmetrically from center


How to update text in WinForms Label control symmetrically from the center if each line here is value update, not the single text, first shows "A", then "New" etc:

            A
           New
           Year
          Comes
          again 
        and again
        to spread 
      the spirit and
     Celebration have 
   a wonderful New Year 
 party and Happy New Year
    with joy and peace 

Solution

  • Use a StringBuilder with the label's TextAlign property to MiddleCenter and AutoSize to true.

    StringBuilder sb = new StringBuilder();
    sb.AppendLine("A");
    sb.AppendLine("New");
    sb.AppendLine("Year");
    sb.AppendLine("Comes");
    sb.AppendLine("again");
    sb.AppendLine("and again");
    sb.AppendLine("to spread");
    sb.AppendLine("the spirit and");
    sb.AppendLine("Celebration have");
    sb.AppendLine("a wonderful New Year");
    sb.AppendLine("party and Happy New Year");
    sb.AppendLine("with joy and peace");
    
    Label l = new Label();
    l.AutoSize = true;
    l.TextAlign = ContentAlignment.MiddleCenter;
    l.Text = sb.ToString();
    
    Controls.Add(l);