我有一个dynamic创build的表单,在这个表单上有几个在运行时创build的单选button。 在这个表单上有一个button,例如“Next”,当用户点击下一个我想循环,并检查是否有一个单选button被选中之前,我已经尝试了以下几点:
void nextButton_Click(object sender,EventArgs e) { foreach (Control c in _form.Controls) { if (c is RadioButton) { RadioButton radio = c as RadioButton; if (radio is RadioButton) { if (radio.Checked == true) { //code continue to next } else { MessageBox.Show("You must select at least one."); } } } } }
亲切的问候土力工程处
Windows – 直接运行.py与运行python blah.py的行为有所不同
为什么我的ASP.Net网站在IIS7下运行需要很长时间才能加载一段时间的不活动?
LoadImage()返回NULL,GetLastError()返回0
有没有Windows模拟supervisord?
你可以使用Linq来简化它
bool checked = _form.Controls.OfType<RadioButton>().Any(rb => rb.Checked);
– 编辑 –
我更新了递归搜索所有控件的答案。
bool IsChecked(Control parent) { if (parent.Controls.OfType<RadioButton>().Any(rb => rb.Checked)) return true; foreach (Control c in parent.Controls) if (IsChecked(c)) return true; return false; } bool checked = IsChecked(_form);
如果其中一个无线电被选中,你应该退出循环,所以如果找到了一个退出条件。
if (radio.Checked == true) { return; } else { MessageBox.Show("You must select at least one."); }
为了找到嵌套控件,你应该使用:
_form.Controls.Find()
大概你的单选按钮躺在面板里面。 因此单选按钮被列在面板的控件集合中,而不是表单。 试试这个:
private static void CheckRadioButton(Control control) { foreach (Control c in control.Controls) { if (c is RadioButton) { if (((RadioButton)c).Checked == true) { //code continue to next } else { MessageBox.Show("You must select at least one."); return; //should be } } else if (c.Controls.Count > 0) CheckRadioButton(c); } }
void nextButton_Click(object sender,EventArgs e) { CheckRadioButton(this); //or whichever form it is.. }
您不需要不必要的内部循环再次确认控件是否是单选按钮。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。