Reputation: 2616
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;
}
}
Upvotes: 4
Views: 18497
Reputation: 858
GB_Product_Entry.Enabled = false; it will disable all inside in GB_Product_Entry GrpupBox
Upvotes: 0
Reputation: 8214
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
.
Upvotes: 10