禁用 Groupbox 中的所有控件 [英] Disable all controls within Groupbox

查看:71
本文介绍了禁用 Groupbox 中的所有控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试禁用 Groupbox 中的所有控件,如下所示,但在投射任何建议时出现错误?

I am trying to disable all controls within Groupbox as shown below, but I am getting error On casting any suggestion ?

无法将 system.windows.forms.checkbox 类型的对象转换为类型system.windows.forms.textbox

unable to cast object of type system.windows.forms.checkbox to type system.windows.forms.textbox

            foreach (Control cont in GB_Product_Entry.Controls)
            {
                if (cont is TextBox || cont is ComboBox)
                {
                    ((TextBox)cont).ReadOnly = true;
                    ((TextBox)cont).BackColor = SystemColors.Control;

                    ((ComboBox)cont).Enabled = false;
                    ((ComboBox)cont).BackColor = SystemColors.Control;

                    ((CheckBox)cont).Enabled = false;
                    //((CheckBox)cont).BackColor = SystemColors.Control;
                }
            } 

推荐答案

为什么不直接禁用 GroupBox 本身?

Why not just disable the GroupBox itself?

GB_Product_Entry.Enabled = false;

如果你真的必须遍历它们,那么分隔 if 条件:

If you really must loop through them then separate the if conditions:

foreach (Control cont in GB_Product_Entry.Controls)
{
    if (cont is TextBox)
    {
        ((TextBox)cont).ReadOnly = true;
        ((TextBox)cont).BackColor = SystemColors.Control;
    }
    else if (cont is ComboBox)
    {
        ((ComboBox)cont).Enabled = false;
        ((ComboBox)cont).BackColor = SystemColors.Control;
    }
    else if (cont is CheckBox)
    {
        ((CheckBox)cont).Enabled = false;
      //((CheckBox)cont).BackColor = SystemColors.Control;
    }
    // Any other conditions here...
} 

这个问题目前是因为在 if 语句中你将 cont 转换为 TextBox 并且稍后他们将它转换为 ComboBox.好吧,它只能是 on 或 other,所以演员总是在某些时候失败.

The issue is currently caused because inside the if statement you cast cont to TextBox and them moments later cast it to ComboBox. Well it can only be on or the other so the cast always fails at some point.

将语句分开后,您就知道类型,因为它是由 if 过滤的.

With the statements separated you know the type as it's filtered by the if.

这篇关于禁用 Groupbox 中的所有控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆