If else condition on单选按钮



我能够创建按钮。我将使用大约65个按钮,如果其他条件在按钮上,你该如何使用?有人能给我举个例子吗?提前谢谢。

    private void createButtons()
    {
        flowLayoutPanel1.Controls.Clear();
        for(int i = 0;i <10;i++)
        {
            RadioButton b = new RadioButton();
            b.Name = i.ToString();
            b.Text = "radiobutton" + i.ToString();
            b.AutoSize = true;
            flowLayoutPanel1.Controls.Add(b);
        }
    }

把单选按钮放在列表或数组中怎么样?这样就可以使用if (allRadioButtons[1].checked) {...}

以下是的示例

    private List<RadioButton> allRadioButtons = new List<RadioButton>();
    private void createButtons()
    {
        flowLayoutPanel1.Controls.Clear();
        for (int i = 0; i < 10; i++)
        {
            RadioButton b = new RadioButton();
            b.Name = i.ToString();
            b.Text = "radiobutton" + i.ToString();
            b.AutoSize = true;
            flowLayoutPanel1.Controls.Add(b);
            //add every button to the list
            //the one with the Text radiobutton0 will be accessible as allRadioButtons[0]
            //the one with the Text radiobutton1: allRadioButtons[1]
            //etc
            allRadioButtons.Add(b);
        }
    }
    //you can use your list in any other method
    private void myMethod() {
        if (allRadioButtons[0].Checked)
        {
            //do something
        }
    }

如果Andrea的答案不适用(因为您没有将其标记为解决方案),另一种选择是创建一个容器,例如GroupBox,然后将您用程序创建的RadioButton控件添加到此容器中。然后,您可以像这样在属于GroupBox的控件上循环:

foreach (Control c in myGroupBox.Controls)
{
    if ((RadioButton)c).Checked)
        //Do something
}

这将在GroupBox中的所有控件上循环,并将它们强制转换为RadioButton,然后检查它们是否被选中。我在不同的应用程序中使用了类似的东西作为相当多的需求的基础;制作一个递归方法非常容易,该方法使用ControlCollection,对其进行循环,并根据某些条件应用所需的逻辑,例如控件的类型或控件的Tag值。

然后,在运行时将RadioButton添加到GroupBox中,您只需执行类似myGroupBox.Controls.Add(b)的操作,其中b是您在示例代码中的for循环中创建的RadioButton。有关运行时控件创建的更多信息,请点击此处。

最新更新