2014-07-07 215 views
0

爲了避免重複代碼更改多個標籤,我在找了這個以下解決方案:C#通過循環

private void sensor1SetUnits(string newUnit) 
    { 
     foreach (Control ctrl in groupBoxSensor1.Controls) 
     { 
      // initialize all labels 
      if (ctrl is Label) 
      { 
       ((Label)ctrl).Text = newUnit; 
      } 
     } 
    } 

    private void sensor2SetUnits(string newUnit) 
    { 
     foreach (Control ctrl in groupBoxSensor2.Controls) 
     { 
      // initialize all labels 
      if (ctrl is Label) 
      { 
       ((Label)ctrl).Text = newUnit; 
      } 
     } 
    } 
    private void uiInitControls() 
    { 
     sensor1SetUnits(units.celsius); 
     sensor2SetUnits(units.celsius); 
    } 

不過,我已經超過10個groupboxes,我需要每次都在變化標籤到另一個單位。

我希望是這樣的:

private void uiSensorChangeUnits(Control * ptrCtrl) 
    { 
     foreach (Control ctrl in ptrCtrl) 
     { 
      // initialize all labels 
      if (ctrl is Label) 
      { 
       ((Label)ctrl).Text = units.celsius; 
      } 
     } 

    } 

    private void someFunction() 
    { 
     uiSensorChangeUnits(&groupBoxSensor1.Controls); 
     uiSensorChangeUnits(&groupBoxSensor2.Controls); 
    } 
+1

只要看看'Controls'屬性返回的類型。確定你的參數類型,然後你就完成了。 – Servy

+0

是這個'C'還是'C#'? – paqogomez

+0

相關:[通用所有控件方法](http://stackoverflow.com/questions/17454389/generic-all-controls-method) – Sayse

回答

2

你可以通過一個組框的方法,然後尋找適當的控制可以與OfType extension

private void SetSensorUnitLabels(GroupBox currentGB, string newUnit) 
{ 
    foreach (Label ctrl in currentGB.Controls.OfType<Label>()) 
    { 
     ctrl.Text = newUnit; 
    } 
} 


SetSensorUnitLabels(groupBoxSensor1, units.celsius); 
SetSensorUnitLabels(groupBoxSensor2, units.celsius); 
0
private void UpdateUnitLabels(GroupBox groupBox, string unit) 
{ 
    foreach (Control control in groupBox.Controls) 
    { 
     var label = control as Label; 
     if (Label != null) 
     { 
      label.Text = unit; 
     } 
    } 
} 
1

好可以減少LINQ是你最好的選擇。

private void Form1_Load(object sender, EventArgs e) 
    { 
     UpdateChildrenInGroupBox<Label>("Test Label"); 
     UpdateChildrenInGroupBox<TextBox>("Test Textbox"); 

     //Wont compile 
     //UpdateChildrenInGroupBox<Rectangle>("Test Rectangle"); 
    } 

    private void UpdateChildrenInGroupBox<T>(string value) where T: Control 
    { 
     var allGBs = this.Controls.OfType<GroupBox>(); 
     var allControlsInGBs = allGBs.SelectMany(f => f.Controls.Cast<Control>()); 
     allControlsInGBs.OfType<T>().ToList().ForEach(f => f.Text = value); 
    } 

我們循環槽的所有窗體,其中有類型組框。然後我們選擇控件並將它投射給它們。然後我們得到傳入的類型並設置它們的值。