当动态创建按钮时,如何在if else语句上调用单个单选按钮?

时间:2015-12-13 15:49:42

标签: c# winforms if-statement radio-button

我有以下代码,在本论坛的某个人的button1_Click中,我无法弄清楚下一步是什么。假设我有4个单选按钮,有人可以向我展示如何在单击button2时根据各自的if else语句对每个单独的单选按钮使用if else语句的示例吗?

var list = new List<string>
{
    "First radio text", "Second radio text", "Third radio text", "And so on"
};

this.panel1.SuspendLayout();
for (var i = 0; i < list.Count; i++)
{
    var r = new RadioButton();
    r.Text = list[i];
    r.Tag = i;
    r.Name = string.Format("r{0}", i);
    r.Dock = DockStyle.Top;
    r.CheckedChanged += r_CheckedChanged;
    this.panel1.Controls.Add(r);
    r.BringToFront();
}
this.panel1.ResumeLayout(true);

1 个答案:

答案 0 :(得分:0)

您可以通过名称检查发送事件的单选按钮:

private void r_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton radio = sender as RadioButton;

            if (radio.Name == "r1")
                MessageBox.Show("Radio 1 checked changed to: " + radio.Checked);
            else if (radio.Name == "r2")
                MessageBox.Show("Radio 2 checked changed to: " + radio.Checked);
            else if (radio.Name == "r3")
                MessageBox.Show("Radio 3 checked changed to: " + radio.Checked);
            else
                MessageBox.Show("Unknow radio button");
        }