2012-09-22 62 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; 
} 
相關問題