如何禁用按钮列表

时间:2015-02-11 09:35:55

标签: c# winforms

我在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;
                    }
                }
            }

任何人都可以看到为什么这不会禁用我的按钮。

欢迎任何建议。

4 个答案:

答案 0 :(得分:5)

为什么不简单?:

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

答案 1 :(得分:0)

如果直接添加到表单中,那么您只需预览控件集合和禁用按钮。

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

foreach (var button in buttonsToDisable)
         {
            button.Enabled = false;
         }

答案 2 :(得分:0)

currentButton.Enabled = false;
this.Controls.Add(currentButton);

答案 3 :(得分:0)

回答你的问题 - 如果按钮是表格的直接后代,你的代码就会起作用 - 即它们被直接放在它上面。 但是,如果您将它们放在另一个容器(例如组合框)中,那么您的代码需要更改为:

 foreach (var control in groupBox1.Controls)

如果你有多个级别的复杂性,那么你将看到一个递归函数来获取父母及其父母等的按钮。

正如其他人所指出的那样,你总是可以遍历buttonsToDisable。