Search code examples
c#winformsflowlayoutpanel

How to center align multiple radio buttons in FlowLayoutPanel?


I'm using windows forms and trying to add multiple radio buttons on a FlowLayoutPanel. I might add 10-12 radio buttons dynamically and might remove them, but all the time they will be at the center of the FlowLayoutPanel. Currently they are being added like the picture below: enter image description here


Solution

  • To fine-tune positions of controls in their containers you can modify their Margin property.

    Assuming you have the controls to center in a list:

    List<Control> ctls = new List<Control>();
    foreach (Control c in flowLayoutPanel1.Controls) ctls.Add(c);
    

    You can call a function to align them:

    void centerControls(List<Control> ctls, Control container)
    {
        int w = container.ClientSize.Width;
        int marge = (w - ctls.Sum(x => x.Width)) / 2;
        Padding oldM = ctls[0].Margin;
        ctls.First().Margin = new Padding(marge, oldM.Top, oldM.Right, oldM.Bottom);
        ctls.Last().Margin = new Padding(oldM.Left, oldM.Top, oldM.Right, marge);
    }
    

    enter image description here

    enter image description here

    Call the function whenever you have added or removed a control:

    centerControls(ctls, flowLayoutPanel1);
    

    You will need to reset the Margins when you add new Buttons..

    Note that I only change the outer Margins, not the space between. To do the latter you can calculate the space and change Margins for all controls:

    enter image description here

    void spaceControls(List<Control> ctls, Control container)
    {
        int w = container.ClientSize.Width;
        int marge = (w - ctls.Sum(x => x.Width)) / (ctls.Count * 2 );
        Padding oldM = ctls[0].Margin;
        Padding newM = new Padding(marge, oldM.Top, marge, oldM.Bottom);
        foreach (Control c in ctls) c.Margin = newM;
    }
    

    Also do think of what shall happen when more than one row of RadioButtons is there! You may want to put more effort in maintinang the List(s)..

    Also note that users do not like their controls to jump around a lot!

    Update: Do have a look ar Reza's post here and here for ways to achieve something like the 1st layout in a code-free way!