You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在循环中为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:36:03