如何以编程方式创建单选按钮?

时间:2014-05-04 01:32:01

标签: c# winforms radiobuttonlist

我试图创建一个从数据库中获取值并将它们放入单选按钮的程序。但是,单选按钮的数量可能会因数据库中的每个项目而改变,因此我会以编程方式创建单选按钮。

但是,我在尝试使整个单选按钮列表居中时遇到了困难。理想情况下,我希望选项列表在最大化窗口的中间水平居中 - 任何提示?

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]);
}

1 个答案:

答案 0 :(得分:0)

// 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);