Search code examples
c#winformslayoutautosize

Is there a way to auto-width or auto-height a control in C# WinForms?


I have a FlowLayoutPanel with some buttons inside. I want the FlowLayoutPanel width to be the same as the biggest button, but the height to be fixed. How can I accomplish that? I have googled it but all I found was about WPF.


Solution

  • You can simply LINQ through the controls and find the maximum width of your buttons:

    int maxWidth = flp.Controls.OfType<Button>().Max(x => x.Width) + 
                  (flp.Margin.Left + flp.Margin.Right);
    flp.ClientSize = new Size(maxWidth, flp.ClientSize.Height);