2015-02-11 26 views
-1

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

任何人都可以明白爲什麼這不會禁用按鈕我。

歡迎任何建議。

+3

哪裏有按鈕?他們是表格的直接子嗎? – 2015-02-11 09:37:11

+0

在您的示例中,將'foreach(this.Controls中的var控件)'更改爲'foreach(buttonsToDisable中的var控件)' – user3256944 2015-02-11 09:39:32

+0

Controls集合只包含控件或窗體的直接子項。因此,坐在面板或標籤等上的任何按鈕都不在其中。你可以寫一個遞歸函數,或者簡單地使用你已經擁有的列表,這是更有效的。 – TaW 2015-02-11 09:43:58

回答

5

爲什麼就不能?:

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

我一直在想這完全謝謝這工作 – Inkey 2015-02-11 09:52:34

0

如果直接添加到窗體,然後你剛剛的foreach Controls集合和禁用按鈕。

 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; 
     } 
0
currentButton.Enabled = false; 
this.Controls.Add(currentButton); 
0

回答你的問題 - 如果按鈕爲形式的直接後裔您的代碼將工作 - 也就是說,它們被放置在直它。 然而,如果你把他們安置在另一個容器(如組框),那麼你的代碼需要改變的東西,如:

foreach (var control in groupBox1.Controls) 

如果你有複雜的多層次,那麼你會看一個遞歸函數去父母和他們的父母等按鈕。

正如其他人指出的,你總是可以遍歷buttonsToDisable。