一、博客背景
博主做C#作业时遇到了一个难题,那就是如何选择GroupBox中被选中的RadioButton和CheckBox和ComBox被选中的items,经过查阅相关资料,了解到可以用foreach遍历GropuBox中的Controls属性来获取被选中的按钮或者复选框;可以用Combox控件的SelectedItem属性来获取当前选定项,如果未从列表中选择,该属性值为空。
二、博客代码
1.选择GroupBox中被选中的RadioButton和CheckBox
//这是选择GroupBox被选中的RadioBUtton
foreach (Control ctr in groupBox1.Controls)
{
if(ctr is RadioButton && (ctr as RadioButton).Checked)
{
//括号中的代码是博主作业所用到的
//大家可以在此处修改代码服务于自己的项目
string value = ctr.Text;
obj[i++] = value;
}
}
//这是选择GroupBox被选中的CheckBox
foreach(Control ctr in groupBox3.Controls)
{
if(ctr is CheckBox && (ctr as CheckBox).Checked)
{
//括号中的代码是博主作业所用到的
//大家可以在此处修改代码服务于自己的项目
String value =ctr.Text;
obj[i++] = value;
}
}
2.选择ComBox被选中的items
//obj[i++]是博主作业所用到的代码
obj[i++] = comboBox1.SelectedItem;
三、代码成果展示
图 1 代码成果展示图