簡體   English   中英

循環控制

[英]Looping through controls

在我的代碼中,我需要遍歷GroupBox中的控件並僅在它是ComboBox時處理控件。 我正在使用代碼:

foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls)
{
    if (grpbxChild.GetType().Name.Trim() == "ComboBox")
    {
        // Process here
    }
}

我的問題是:不是循環遍歷所有控件而只處理組合框,而只能從GroupBox中獲取組合框? 像這樣的東西:

foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls.GetControlsOfType(ComboBox))
{
    // Process here
}

由於您使用的是C#2.0,因此您運氣不佳。 你可以自己寫一個函數。 在C#3.0中你只需:

foreach (var control in groupBox.Controls.OfType<ComboBox>())
{
    // ...
}

C#2.0解決方案:

public static IEnumerable<T> GetControlsOfType<T>(ControlCollection controls)
    where T : Control
{
    foreach(Control c in controls)
        if (c is T)
            yield return (T)c;
}

您使用的方式如下:

foreach (ComboBox c in GetControlsOfType<ComboBox>(groupBox.Controls))
{
    // ...
}

Mehrdad非常正確,但您的語法(即使您使用的是C#2.0)也過於復雜。

我發現這更簡單:

foreach (Control c in gpBx.Controls) 
{ 
  if (c is ComboBox) 
  { 
    // Do something.
  }
}
foreach (Control items in this.Controls.OfType<GroupBox>())
{
    foreach (ComboBox item in items.Controls.OfType<ComboBox>())
    {
        // your processing goes here
    }
}
if (!(grpbxChild is System.Windows.Forms.Combobox)) continue;

// do your processing goes here
grpbxChild.Text += " is GroupBox child";
foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls)
{
    if (grpbxChild is ComboBox)
    {
        // Process here
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM