禁用 Groupbox 中的所有控件 [英] Disable all controls within 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屋!