0

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.

Jess
  • 42,368
  • 6
  • 37
  • 51

2 Answers2

2

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
  • 11,666
  • 5
  • 47
  • 58
1

If this is your actual code, then it is not Flowing at all. It implements a WPF stackPanel, and you can get the same effect by setting Dock=DockStyle.Top for all controls. Dock is available in CF.

H H
  • 263,252
  • 30
  • 330
  • 514