Articles in this section
Category / Section

How to use the WinForms FlowLayout to autosize the label control on a form?

2 mins read

Use the FlowLayout to autosize the label

The FlowLayout can be used to provide autosizing behavior for a label control on a form. The .NET label control can now expand/collapse horizontally as the form width is increased or decreased.

To set up this behavior:

- Set the Minimumsize property for the form.

- For the FlowLayout component, set the LayoutMode to Vertical and provide LeftMargin and RightMargin.

- To autosize the label with the text, you need to listen to the FlowLayout's ProvideLayoutInformation event to set the PreferredSize for the label control. You have to do this because the .NET label control does not have a concept of Preferredsize.

C#

private void flowLayout1_ProvideLayoutInformation(object sender, Syncfusion.Windows.Forms.Tools.ProvideLayoutInformationEventArgs e)
{
   if (e.Control == this.label1 && e.Requested == LayoutInformationType.PreferredSize)
   {
       Graphics g = this.CreateGraphics();   SizeF szPref = g.MeasureString(this.label1.Text, this.label1.Font, this.ClientRectangle.Width);
       e.Size = new Size(this.ClientRectangle.Width-20, (int)szPref.Height + 5);
       e.Handled = true;
       g.Dispose();
   }
}

VB

Private Sub flowLayout1_ProvideLayoutInformation(ByVal sender As Object, ByVal e As Syncfusion.Windows.Forms.Tools.ProvideLayoutInformationEventArgs)
   If e.Control = Me.label1 And e.Requested = LayoutInformationType.PreferredSize Then
       Dim g As Graphics = Me.CreateGraphics()   Dim szPref As SizeF =  g.MeasureString(Me.label1.Text,Me.label1.Font,Me.ClientRectangle.Width)
       e.Size = New Size(Me.ClientRectangle.Width-20, CType(szP.Height + 5, Integer))    
       e.Handled = True   
       g.Dispose()
   End If
End Sub

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied