Search code examples
c#winformsflowlayoutpanel

c# assign a button custom location on FlowLayoutPanel


I have a FlowLayoutPanel on which I have some Buttons ordered vertically (the panel ordered automatically just the way I wanted). But now I want to place another button1 but with a custom location (at the top right corner of FlowLayoutPanel). So far I tried button1.Location = new Point(x,y); but the button1 is still placed in order. Can you help me? Thanks


Solution

  • If you want to position a control in your desired location you're using a wrong container. FlowLayouPanel as name suggests it arranges its children in a flow manner.

    Either use simple Panel or create a custom LayoutEngine.

    To answer your another question: To place buttons vertically you can do this.

    Point location = Point.Empty;
    foreach (Button button in buttons)
    {
        button.Location = location;
        location.Y += button.Height;
        location.Y += 10;//Add some space
    }
    

    Another approach is to use descendant of FlowLayoutPanel and override the OnLayout method like this.

    public class MyFlowLayoutPanel : FlowLayoutPanel
    {
        protected override void OnLayout(LayoutEventArgs levent)
        {
            base.OnLayout(levent);
    
            var button = flowLayout.Controls.OfType<Button>().FirstOrDefault();
            if (button != null)
                button.Location = new Point(flowLayout.Width - button.Width, 0);
        }
    }