如何在循环中为Controls.Find查找的CheckBox设置Checked选中状态
问题原因
Controls.Find() 方法返回的对象是所有控件的基类 Control 类型,该类型本身没有定义 Checked 属性,只有 CheckBox 子类才支持这个属性,所以直接调用会提示属性不存在。
修复方案
建议加上空值和类型校验逻辑,避免找不到控件或者类型不匹配引发运行时崩溃,完整代码如下:
for (int i = 0; i < Program.productOperationCount; i++) { // 查找对应名称的控件 Control[] foundControls = this.Controls.Find($"checkBox{i + 1}", true); // 校验控件存在且是CheckBox类型 if (foundControls.Length > 0 && foundControls[0] is CheckBox targetCheckBox) { targetCheckBox.Visible = true; targetCheckBox.Checked = true; } }
如果能100%确认查找的控件一定存在且是CheckBox类型,也可以直接强制转换,简化写法如下:
for (int i = 0; i < Program.productOperationCount; i++) { this.Controls.Find($"checkBox{i + 1}", true)[0].Visible = true; // 强制转换为CheckBox类型后访问Checked属性 ((CheckBox)this.Controls.Find($"checkBox{i + 1}", true)[0]).Checked = true; }
内容的提问来源于stack exchange,提问作者Mantvydas Smilgis
相关产品推荐
相关产品推荐

