Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable all controls within Groupbox

Tags:

c#

winforms

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

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;
                }
            } 
like image 991
sam Avatar asked Oct 16 '25 16:10

sam


1 Answers

Why not just disable the GroupBox itself?

GB_Product_Entry.Enabled = false;

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...
} 

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.

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

like image 153
Equalsk Avatar answered Oct 18 '25 07:10

Equalsk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!