我在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;
}
}
}
任何人都可以明白爲什麼這不會禁用按鈕我。
歡迎任何建議。
哪裏有按鈕?他們是表格的直接子嗎? – 2015-02-11 09:37:11
在您的示例中,將'foreach(this.Controls中的var控件)'更改爲'foreach(buttonsToDisable中的var控件)' – user3256944 2015-02-11 09:39:32
Controls集合只包含控件或窗體的直接子項。因此,坐在面板或標籤等上的任何按鈕都不在其中。你可以寫一個遞歸函數,或者簡單地使用你已經擁有的列表,這是更有效的。 – TaW 2015-02-11 09:43:58