[英]WinForms and C#: How to disable buttons in a groupbox?
My goal is to disable all buttons (1 and 2) in groupbox1 (see the picture at the end).我的目标是禁用 groupbox1 中的所有按钮(1 和 2)(见最后的图片)。 When I call the following Method DisableAllButtons(), only button 3 is disabled.
当我调用以下方法 DisableAllButtons() 时,只有按钮 3 被禁用。 What am i doing wrong?
我究竟做错了什么?
private void DisableAllButtons()
{
try
{
foreach (Control c in Controls)
{
Button button = (Button)c;
button.Enabled = false;
}
}
catch
{
}
}
It's because you are using the Controls
on your loop.这是因为您在循环中使用了
Controls
。 So you are calling all the controls that is on your form which is the Button3
and not the controls inside your GroupBox.因此,您正在调用表单上的所有控件,即
Button3
,而不是 GroupBox 中的控件。
To do that, you can do this.为此,您可以这样做。
public void DisableButton()
{
List<Button> btn = groupBox1.Controls.OfType<Button>().ToList();
foreach (var b in btn)
{
b.Enabled = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.