如何从combobox中选中哪个单选按钮?
我有这些组框:
我想根据检查的单选按钮的真实状态运行一些代码,如:
string chk = radiobutton.nme; // Name of radio button whose checked is true switch(chk) { case "Option1": // Some code break; case "Option2": // Some code break; case "Option3": // Some code break; }
有没有直接的方法,所以我只能得到已选中的单选按钮的名称?
您可以找到所有选中的RadioButtons
var buttons = this.Controls.OfType() .FirstOrDefault(n => n.Checked);
另请CheckedChanged
事件。
Checked属性的值更改时发生。
您应该查看CheckedChanged
事件以注册相应的事件处理程序并将Checked
单选按钮状态存储在某个变量中。 但是,我想在这里使用LINQ只是因为你只有一些RadioButtons
,这使得循环的成本可以接受:
var checkedRadio = new []{groupBox1, groupBox2} .SelectMany(g=>g.Controls.OfType() .Where(r=>r.Checked)) // Print name foreach(var c in checkedRadio) System.Diagnostics.Debug.Print(c.Name);
而不是检查所有RadioButtons,使用GroupBox的Validated事件。
private void grpBox_Validated(object sender, EventArgs e) { GroupBox g = sender as GroupBox; var a = from RadioButton r in g.Controls where r.Checked == true select r.Name; strchecked = a.First(); }
在我看来,如果你使用RadioGroup而不是GroupBox,那就更好了。 如果您使用radioGroup,您始终可以轻松地找到所选项目,如下所示:
radioGroup.selectedIndex;
如果你使用Windows Forms进行设计,我建议像这样实现RadioGroup行为(请注意我的代码是用Java编写的):
for (Component comp:groupBox1.components) { if (((RadioButton)comp).selected) return ((RadioButton)comp).value; }
您可以将此代码块放在方法中以返回所选的radioButton值,然后您可以在SWITCH部分中使用此值。