如果单击button3,它应该对11个radiobutton中的一个执行单击。 这个程序有效,但我想知道是否有更短的输入方式。
我想知道,因为如果我想用50个无线电按钮做这个,那么这将是一个极长的。
private void button1_Click(object sender, EventArgs e)
{
Random RandomRadioButton = new Random();
int Simuleer = RandomRadioButton.Next(0, 12);
if (Simuleer == 0) { radioButton0.PerformClick(); }
if (Simuleer == 1) { radioButton1.PerformClick(); }
if (Simuleer == 2) { radioButton2.PerformClick(); }
if (Simuleer == 3) { radioButton3.PerformClick(); }
if (Simuleer == 4) { radioButton4.PerformClick(); }
if (Simuleer == 5) { radioButton5.PerformClick(); }
if (Simuleer == 6) { radioButton6.PerformClick(); }
if (Simuleer == 7) { radioButton7.PerformClick(); }
if (Simuleer == 8) { radioButton8.PerformClick(); }
if (Simuleer == 9) { radioButton9.PerformClick(); }
if (Simuleer == 10) { radioButton10.PerformClick(); }
if (Simuleer == 11) { radioButton11.PerformClick(); }
}
答案 0 :(得分:1)
如果是WinForms
,请尝试以下操作:
string name = string.Format("radioButton{0}", Simuleer);
this.Controls/* or container that groups thease radio buttons */
.OfType<RadioButton>().FirstOrDefault(ctrl => ctrl.Name == name).PerformClick();
答案 1 :(得分:0)
这有点长,但这段代码将来很容易维护。
将RadioButtonList
与Separate Radio buttons
进行比较。
protected void Button1_Click(object sender, EventArgs e)
{
Random random = new Random();
var radioButtonNumber = random.Next(RadioButtonList1.Items.Count);
RadioButtonList1.SelectedIndex = radioButtonNumber;
RadioButtonListClick(radioButtonNumber);
}
private void RadioButtonListClick(int number)
{
switch (number)
{
case 0:
// Call the function realted to radio button 0 in your case.
break;
.
.
.
}
}
注意:这将确保在编译时此代码在运行时不会失败。与确保radiobutton
id应该相同并且如果找不到它相比,它会抛出运行时错误。