RadioButton控件name包含"OFF"都为选中状态

tabControl1控件中,所有RadioButton控件中name包含“OFF”字样的,为选中状态。代码怎样写呢?

可以通过遍历 tabControl1 中的所有 RadioButton 控件,判断控件的 Name 属性是否包含字符串 "OFF",如果包含则将控件的 Checked 属性设置为 true。

以下是一个示例代码:

foreach (Control c in tabControl1.Controls)
{
    if (c is RadioButton && c.Name.Contains("OFF"))
    {
        ((RadioButton)c).Checked = true;
    }
}


在代码中,首先通过 foreach 循环遍历 tabControl1 中的所有控件,然后使用 is 关键字判断控件是否是 RadioButton 类型,同时判断控件的 Name 属性是否包含字符串 "OFF"。如果满足条件,则将控件强制转换为 RadioButton 类型,并将 Checked 属性设置为 true。

该回答引用ChatGPT

假设你使用的是 C# 语言,并且在 Windows 窗体应用程序中使用了名为 tabControl1 的选项卡控件,其中包含多个 RadioButton 控件,你可以使用以下代码来查找并选中所有 name 属性包含“OFF”字样的 RadioButton 控件:



foreach (Control tabPage in tabControl1.TabPages) // 遍历所有选项卡
{
    foreach (Control control in tabPage.Controls) // 遍历当前选项卡的所有控件
    {
        if (control is RadioButton && control.Name.Contains("OFF")) // 判断是否为 RadioButton 控件并且 name 属性包含“OFF”字样
        {
            ((RadioButton)control).Checked = true; // 设置为选中状态
        }
    }
}

以上代码使用了两个嵌套的 foreach 循环,分别遍历了 tabControl1 中的所有选项卡和当前选项卡中的所有控件。使用 is 关键字判断控件是否为 RadioButton 控件,并使用 Name.Contains 方法判断 name 属性是否包含“OFF”字样。如果满足条件,则将该控件的 Checked 属性设置为 true,即选中状态。

请注意,上述代码中使用了强制类型转换,将控件转换为 RadioButton 类型,因此如果选项卡中存在其他类型的控件或 RadioButton 控件中不包含“OFF”字样的 name 属性,则会出现运行时异常。在实际开发中,应该根据具体的需求进行适当的异常处理和数据验证