views:

440

answers:

1

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.

+1  A: 

You can either set Dock=DockStyle.Top on all of your controls, or you can use an OwnerDraw listbox (I use the one from OpenNetCF.com). It depends on how many items you have to display. I have found that using the OwnerDraw ListBox is faster when you have a lot of items, but the Panel approach is easier to develop.

One note: Call SuspendLayout before you add your controls, and ResumeLayout when you are done.

Chris Brandsma