Search code examples
c#winformsradiobuttonlist

how to center programmatically created radio buttons?


I'm trying to create a program which grabs values from a database and puts them into radio buttons. However, the number of radio buttons may change for every item in my database, so I'm creating the radio buttons programmatically.

However, I'm having difficulties trying to get the entire list of radio buttons to be centered. Ideally, I want the list of options to be horizontally centered in the middle of a maximized window - any tips?

System.Windows.Forms.RadioButton[] radioButtons =
    new System.Windows.Forms.RadioButton[answersItems];

for (int i = 0; i < answersItems; ++i)
{
    radioButtons[i] = new RadioButton();
    radioButtons[i].Font = new Font("Calibri", 20);
    radioButtons[i].Location = new System.Drawing.Point((1600/2) - (radioButtons[i].Text./2), question.Location.Y + question.Height + 38 + i * 38);
    radioButtons[i].AutoSize = true;
    this.Controls.Add(radioButtons[i]);
}

Solution

  • // Get all the RadioButtons on the form.
    var allRadioButtons = this.Controls.OfType<RadioButton>().ToArray();
    
    // Get the width of the widest RadioButton.
    var greatestWidth = allRadioButtons.Max(rb => rb.Width);
    
    // Calculate the X position to centre the widest RadioButton.
    var commonLeft = (this.ClientSize.Width - greatestWidth) / 2;
    
    // Align all RadioButtons to the calculated X position.
    Array.ForEach(allRadioButtons, rb => rb.Left = commonLeft);