启用或禁用表单上的所有控件
问题描述:
如果我的表单上有N个按钮。如何禁用表单上的所有按钮而不使用
If i have N amount of button on my form. How do i disable all the buttons on my form without wrting
btn1.enable = false ... btnN.enable = false
提前感谢。
thanks in advance.
答
有两种方法,但最简单的方法可能只是在Form.Controls集合上使用For Each循环。在你检查每个控件并检查它是否是一个按钮时,启用/禁用它们所有这些都是一件简单的事情,而不需要参考这些名称。
你能给我一个简单的代码吗?对于winform而不是WPF ..
There are a couple of ways, but the easiest way is probably just to use a For Each loop on the Form.Controls collection. Of you examine each control and check if it is a button, it's a simple matter to enable / disable all of them without referencing the names at all.
"Can you provide me a simple code please ? for winform not WPF.."
Public Sub EnableControls(controls As Control.ControlCollection, enable As Boolean)
For Each c As Control In controls
c.Enabled = enable
EnableControls(c.Controls, enable)
Next
End Sub
然后从Form类中调用它:
Then call it from your Form class with:
EnableControls(Controls, True)
放入所有按钮
在面板
(或任何其他容器,如GroupeBox
等),只需启用此一个。
(如果你的设计中可能的话)
Put all yourButtons
in aPanel
(or any other Container, likeGroupeBox
, etc) and just enable this one.
(if its possible in your Design)
private void Form1_Load(object sender, EventArgs e)
{
System.Windows.Forms.Control.ControlCollection controls = this.Controls;
foreach(Control ctrl in controls)
{
if (ctrl is Button)
{
ctrl.Enabled = false;
}
}
}