2012-09-22 64 views
0

我有一个包含此GroupControl中的GroupControl的窗体,有一些控件。为GroupControl中的所有控件创建一个仅foreach循环

我想,当我点击一个按钮的THOS控件的属性更改为control.Properties.ReadOnly = false;

所以我创造了这个代码:

 foreach (TextEdit te in InformationsGroupControl.Controls) 
     { 
      te.Properties.ReadOnly = false; 
     } 

     foreach (TextEdit te in InformationsGroupControl.Controls) 
     { 
      te.Properties.ReadOnly = false; 
     } 
     foreach (DateEdit de in InformationsGroupControl.Controls) 
     { 
      de.Properties.ReadOnly = false; 
     } 
     foreach (ComboBoxEdit cbe in InformationsGroupControl.Controls) 
     { 
      cbe.Properties.ReadOnly = false; 
     } 
     foreach (MemoEdit me in InformationsGroupControl.Controls) 
     { 
      me.Properties.ReadOnly = false; 
     } 
     foreach (CheckEdit ce in InformationsGroupControl.Controls) 
     { 
      ce.Properties.ReadOnly = false; 
     } 

这是工作,但我要创建的每一个foreach循环控制。

我也试过这个

foreach (Control control in InformationsGroupControl.Controls) 
{ 
    control.Properties.ReadOnly = false; 
} 

但System.Windows.Forms.Control的不包含定义“属性”

我如何可以创建在所有控件一个唯一的foreach循环GroupControl?

+1

尝试使用'dynamic'。查找MSDN如果你不知道它是什么。要使用它,只需用'动态控制'替换'Control control'。 – 2012-09-22 17:21:36

+0

我不能使用动态类型,它给了我这个错误: '无法找到类型或命名空间名称'dynamic'(您是否缺少using指令或程序集引用?)' –

+0

'dynamic' was introduced在'C#4'中。你使用什么版本? – 2012-09-22 17:51:33

回答

2

它看起来像你使用的一组控件都来自同一个BaseClass。那是BaseClass,BaseEdit?

如果是这样,这样做...

foreach(object control in InformationsGroupControl.Controls) 
{ 
    BaseEdit editableControl = control as BaseEdit; 
    if(editableControl != null) 
     editableControl.Properties.ReadOnly = false; 
} 

我从这个链接使这一猜测(它就像你正在使用的一个的控制)。 http://documentation.devexpress.com/#WindowsForms/DevExpressXtraEditorsBaseEditMembersTopicAll

+0

GroupControl中还有其他控件,如LabelControl和ButtonControl,以便我不能使用该代码。 我想我必须为其他控件制定一个例外,但我不知道如何! –

+0

是的..我试过这个,但它给了我这个代码 'foreach(BaseEdit在InformationsGroupControl.Controls) { be.Properties.ReadOnly = false; }' 但它给了我这个错误: '无法转换类型'DevExpress.XtraEditors.LabelControl为键入“DevExpress.XtraEditors.BaseEdit'.' –

+0

“对象的对象不包含定义”属性'没有扩展方法'属性'接受类型'对象'的第一个参数可以找到 –

1

我更喜欢基类方法。但是,因为你只说了几句类型必须是“只读=假”,你可以做这样的事情

foreach (Control c in InformationsGroupControl.Controls) 
{ 
    if(c is TextEdit || c is DateEdit || c is ComboBoxEdit || c is MemoEdit || c is CheckEdit) 
     (c as BaseEdit).Properties.ReadOnly = false; 
} 
0

incluide LINQ。

USSE下面的代码:

foreach (var edit in InformationsGroupControl.Controls.OfType<BaseEdit>()) 
{ 
    edit.Properties.ReadOnly = false; 
} 
相关问题