I'm writing an application in .NET 2.0 and I need the functionality of a FlowLayoutPanel
from WinForms. This is the code I came up with that I'm using right now (mostly with labels):
/// <summary>
/// Flowable layout panel
/// </summary>
public partial class FlowLayoutPanel : Panel
{
public FlowLayoutPanel()
{
InitializeComponent();
}
/// <summary>
/// Flow the layout of the panel. Required before presentation.
/// </summary>
public void Layout()
{
int top = 0;
// Set control position
foreach (Control ctrl in this.Controls)
{
ctrl.Top = top;
// Account for the scrollbar
ctrl.Width = this.Width - 17;
top += ctrl.Height;
}
}
}
The panel is added to the form (in my case, a dynamically generated tab page), then I add controls in the code view of the form, like this:
panel.Controls.Add(new Label() { Text = "Item name", Font = boldTahoma });
panel.Controls.Add(new Label() { Text = item.ItemName });
panel.Controls.Add(new Label() { Text = "Category", Font = boldTahoma });
panel.Controls.Add(new Label() { Text = item.Category });
panel.Controls.Add(new Label() { Text = "Quantity", Font = boldTahoma });
panel.Controls.Add(new Label() { Text = item.Quantity });
panel.Layout();
So I suppose I have two questions. It works, but is there a better way to do this (especially so I don't have to call Layout()
every time) and is there a way so I can make labels auto-height? Thanks.