2011-06-21 11 views

答えて

9
List<Control> list = new List<Control>(); 

      GetAllControl(this, list); 

      foreach (Control control in list) 
      { 
       if (control.GetType() == typeof(Button)) 
       { 
        //all btn 
       } 
      } 

     private void GetAllControl(Control c , List<Control> list) 
     { 
      foreach (Control control in c.Controls) 
      { 
       list.Add(control); 

       if (control.GetType() == typeof(Panel)) 
        GetAllControl(control , list); 
      } 
     } 
1

この

foreach (var control in this.Controls) 
{ 
    if (control.GetType()== typeof(Button)) 
    { 

     //do stuff with control in form 
    } 

    else if (control.GetType() == typeof(Panel)) 
    { 
     var panel = control as Panel; 
     foreach (var pan in panel.Controls) 
     { 
      if (pan.GetType() == typeof(Button)) 
      { 

       //do stuff with control in panel 
      } 
     } 
    }    

} 
+1

ボタンのあるパネルがパネルに含まれている場合、再帰が使用できます。 –

+0

@Nakul:ああ、あなたは正しい答えを@hashi Rは完全にOKです。 –

5
を試してみてください

これは私が行ったことです ボタンをクリックすると簡単な関数を書いて、パネルコントロールのみを選択して、そのパネル上のコントロールをさらにループする関数に渡します。

private void cmdfind_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      foreach (Control control in this.Controls) 
      { 
       if (control.GetType() == typeof(Panel)) 
        //AddToList((Panel)control); //this function pass the panel object so further processing can be done 
      }       
     } 
     catch (System.Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

    } 
関連する問題