且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Windows窗体C#中禁用所有按钮控件

更新时间:2022-12-23 13:46:40

Q1:禁用相对容易:

Q1: Disable is relatively easy:
foreach (Control c in Controls)
   {
   Button b = c as Button;
   if (b != null)
      {
      b.Enabled = false;
      }
   }

如果你使用任何容器,比如Panels,你可能想把它放在一个方法中,并通过每个control.Controls集合使用递归来获取它们中的按钮。





Q2:不要!这是可能的,但这是一种非常糟糕的做法,因为它违反了OOP的原则。当您直接访问不同表单上的控件时,您将两个表单的设计绑定在一起,因此您无法在不考虑另一个表单的影响的情况下进行更改 - 这也会使重用代码变得更加难以进行维护一个PITA。



相反,使用目标表单上的一个属性来完成实际工作,并从另一个表单中进行更改。如果要更改父表单上的值,则会出现复杂问题,因为您甚至不应该知道父表单存在!在这种情况下,您应该在子级中创建一个事件,父级处理该事件以说明新数据可用以及子级中提供新字符串的属性。父母然后获取新文本并设置它自己的标签。

If you use any containers such as Panels, you may want to put this in a method and use recursion through each control.Controls collection to get the buttons within them.


Q2: Don''t! It is possible, but it is a very bad practice because it is against the principles of OOPs. When you access controls on a different form directly, you tie the design of the two forms together, so you can''t change one without considering the effects on the other - this also makes it a lot harder to reuse your code which makes maintenance a PITA.

Instead, use a property on the target form which does the actual work, and change that from the other form. The complication comes if you want to change the value on a parent form, because you should not even know the parent exists! In that case, you should create an event in the child which the parent handles to say "new data available" and a property in the child which supplies the new string. The parent then gets the new text and sets it''s own label.


我没有得到你的知识,但从我的理解,这是一种方法:



i didnt get u clealy, but from what i have understood, here is a method:

Form ob = new form2();
foreach (Control c in ob.Controls)
 {
   if (c is Label)
     {
        Label lb = (Label)c;
       //if u want to change text of some perticular label in that form then:
       //if(lb.Name.Equals("label's name"))
      lb.Text = "new text";
      }
 }





这将改变form2'标签控件的文本



this will change the text of form2''s label control