2012-06-14 17 views
3

我有喜歡ComboBoxTextBoxCheckBox多個不同的控件Form。我正在尋找一種通用的方式來從這些控件獲取值,同時循環它們。通用的方法來從多個控件獲取值

例如,這樣的事情:

foreach(Control control in controls) 
{ 
    values.Add(control.Value); 
} 

是否有可能還是需要分別對待每control

+1

你得到一個共同財產,如'Text'? –

+1

您可以使用'.Text'屬性 - http://msdn.microsoft.com/fr-fr/library/system.windows.forms.control.text –

+0

哦,沒錯,在MSDN上沒有找到它因爲某些原因。非常感謝。 – mooper

回答

2

試試這個:

Panel myPanel = this.Panel1; 

List<string> values = new List<string>(); 

foreach (Control control in myPanel.Controls) 
{ 
    values.Add(control.Text); 
} 

但要確保你只能得到你想要的控制。您可以檢查的類型,就像

if(control is ComboBox) 
{ 
    // Do something 
} 
+0

是的,這是有效的。我忘了'Text'屬性。 – mooper

2

文本的解決方案是確定的,如果所有的控制是一個文本框,但如果你有一些標籤,你會最終獲得值之間的標籤的文本,除非您填寫你的代碼與if。一個更好的解決方案可能是定義一組委託,對於每種控制返回什麼被視爲值(例如TextBox的Text和CheckBox的CheckBox),將它們放入字典中,並使用它們獲取值每個控制。該代碼可能是這樣的:

public delegate object GetControlValue(Control aCtrl); 

    private static Dictionary<Type, GetControlValue> _valDelegates; 

    public static Dictionary<Type, GetControlValue> ValDelegates 
    { 
     get 
     { 
      if (_valDelegates == null) 
       InitializeValDelegates(); 
      return _valDelegates; 
     } 
    } 

    private static void InitializeValDelegates() 
    { 
     _valDelegates = new Dictionary<Type, GetControlValue>(); 
     _valDelegates[typeof(TextBox)] = new GetControlValue(delegate(Control aCtrl) 
     { 
      return ((TextBox)aCtrl).Text; 
     }); 
     _valDelegates[typeof(CheckBox)] = new GetControlValue(delegate(Control aCtrl) 
     { 
      return ((CheckBox)aCtrl).Checked; 
     }); 
     // ... other controls 
    } 

    public static object GetValue(Control aCtrl) 
    { 
     GetControlValue aDel; 
     if (ValDelegates.TryGetValue(aCtrl.GetType(), out aDel)) 
      return aDel(aCtrl); 
     else 
      return null; 
    } 

然後,你可以寫:

 foreach (Control aCtrl in Controls) 
     { 
      object aVal = GetValue(aCtrl); 
      if (aVal != null) 
       values.Add(aVal); 
     } 
相關問題