简体   繁体   English

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

[英]How Do I call individual radio buttons on if else statement when buttons are created dynamically?

I have the code below, in button1_Click from someone in this forum, I cannot figure out what the next step is. 我有下面的代码,在该论坛中某人的button1_Click中,我无法确定下一步是什么。 Let say I have 4 radio buttons can someone show me an example of how to use the if else statement to each individual radio buttons based on their individual if else statement when I click button2? 假设我有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);

You can check which radio button sent the event by its name: 您可以按名称查看哪个单选按钮发送了事件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM