循环遍历动态表单和面板并检查单选按钮是否选中 [英] loop through a dynamic form and panel and check if radio buttons check or not
本文介绍了循环遍历动态表单和面板并检查单选按钮是否选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个动态创建的表单,在这个表单上有几个在运行时创建的单选按钮.此表单上有一个按钮,例如下一步",当用户单击下一个时我想循环并检查是否选中了其中一个单选按钮,然后再继续,我尝试了以下操作:
I have a form that is dynamically created, on this form are several radio buttons that are created at runtime. There is a button on this form eg "Next" when the user clicks on the next I want to loop through and check if one of the radio buttons are checked before I continue, I have tried the following:
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.");
}
}
}
}
}
亲切的问候地理
推荐答案
你可以使用 Linq 让它更简单
You can use Linq to make it simpler
bool checked = _form.Controls.OfType<RadioButton>().Any(rb => rb.Checked);
--编辑--
我更新了递归搜索所有控件的答案.
I updated the answer to recursively search all controls.
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);
这篇关于循环遍历动态表单和面板并检查单选按钮是否选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文