C# 遍历控件检查是否有被选中的项。这里提供一个思路,实现的方式有两种。这里以CheckBox为例。
思路:从容器控件中一层一层找到CheckBox控件,判断CheckBox是否被选中。
实现方式:
1.判断指定Table容器中的CheckBox是否被选中
1 public static bool IsCheckBox(Table tb_Object) 2 { 3 bool ret = false; 4 if((tb_Object.Controls != null) && (tb_Object.Controls.Count > 0)) 6 { 7 foreach (TableRow tr in tbProject.Controls) 8 { 9 foreach (TableCell tc in tr.Controls) 10 { 11 foreach (Control con in tc.Controls) 12 { 13 if (con is CheckBox) 14 { 15 CheckBox cb = (CheckBox)con; 16 if (cb.Checked) 17 { 18 ret = true; 19 } 20 } 21 } 22 } 23 } 24 } 25 return ret; 26 }
2.通用的递归遍历方式
private static bool IsCheckBox2(Control ctl) { bool ret = false; if((ctl.Controls != null) && (ctl.Controls.Count > 0)) { foreach(Control item in ctl.Controls) { ret = IsCheckBox2(item); if(ret) { break; } } } else { if (ctl is CheckBox) { ret = (ctl as CheckBox).Checked; } } return ret; }