Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何禁用按钮列表_C#_Winforms - Fatal编程技术网

C# 如何禁用按钮列表

C# 如何禁用按钮列表,c#,winforms,C#,Winforms,我在Windows窗体上有许多按钮。我只想禁用其中的一部分 我已经创建了一个按钮列表,并添加了要禁用的按钮。当我运行代码时,按钮仍然处于启用状态 下面是我试过的 private List<Button> buttonsToDisable = new List<Button>(); buttonsToDisable.Add(btn1); buttonsToDisable.Add(btn2); buttonsToDisable.Add(btn3); foreach (

我在Windows窗体上有许多按钮。我只想禁用其中的一部分

我已经创建了一个按钮列表,并添加了要禁用的按钮。当我运行代码时,按钮仍然处于启用状态

下面是我试过的

private List<Button> buttonsToDisable = new List<Button>();
 buttonsToDisable.Add(btn1);
 buttonsToDisable.Add(btn2);
 buttonsToDisable.Add(btn3);

foreach (var control in this.Controls)
            {
                if (control is Button)
                {
                    Button currentButton = (Button)control;

                    if (buttonsToDisable.Contains(currentButton))
                    {
                        currentButton.Enabled = false;
                    }
                }
            }
private List buttonsToDisable=new List();
按钮可修改。添加(btn1);
按钮可修改。添加(btn2);
按钮可修改。添加(btn3);
foreach(此.Controls中的var控件)
{
如果(控制按钮处于关闭状态)
{
按钮currentButton=(按钮)控件;
if(按钮可修改。包含(currentButton))
{
currentButton.Enabled=false;
}
}
}
有人能明白为什么这不能为我禁用按钮吗

欢迎任何建议。

为什么不简单呢

foreach(Button btn in buttonsToDisable)
{
    btn.Enabled = false;
}

如果是直接添加到表单中,那么u只是foreach控制集合和禁用按钮

     Button btn1 = new Button();
     this.Controls.Add(btn1);

     Button btn2 = new Button();
     this.Controls.Add(btn1);

     Button btn3 = new Button();
     this.Controls.Add(btn1);

     buttonsToDisable.Add(btn1);
     buttonsToDisable.Add(btn2);
     buttonsToDisable.Add(btn3);

     foreach (var control in this.Controls)
     {
        ((Button)control).Enabled = false;
     }


回答您的问题-如果按钮是表单的直接后代,您的代码将工作-即,它们直接放置在表单上。 如果您将它们放置在另一个容器(例如groupbox)中,则您的代码需要更改为:

 foreach (var control in groupBox1.Controls)
如果您有多个层次的复杂性,那么您将看到一个递归函数来访问它们的父级和父级中的按钮,等等


正如其他人所指出的,您总是可以迭代ButtonStodiable。

按钮在哪里?它们是窗体的直接子级吗?在您的示例中,将“foreach(此.Controls中的var-control)”更改为“foreach(buttonsToDisable中的var-control)”。控件集合仅包含控件或窗体的直接子级。因此,任何位于面板或选项卡上的按钮都不会在其中。你可以编写一个递归函数,也可以简单地使用你已有的列表,这样效率会更高。我已经仔细考虑过了,谢谢你的工作
currentButton.Enabled = false;
this.Controls.Add(currentButton);
 foreach (var control in groupBox1.Controls)