본문 바로가기

.NET/Winforms

[WINFORMS] Control.ControlCollection 메소드

Control.ControlCollection

  • Control.ControlCollection 클래스는 특정 부모 컨트롤에 대한 자식 컨트롤 목록을 포함한다.
  • 부모 컨트롤에 직접 포함된 모든 컨트롤에 대한 참조를 보유하는 컬렉션

순회를 통해 해당 컨트롤에 있는 자식 컨트롤에 접근이 가능하다.

 foreach (Control control in this.Controls)
 {
     if (control is Button)
     {}
     if (control is ComboBox)
     {}
 ...
 }
 foreach (Control control in this.Controls)
 {
     if (control is Button button) // 즉각 button 이라는 변수로 사용가능
     {}
 }

Control.ControlCollection.Add(Control)

  • 해당 컨트롤에 자식 컨트롤을 추가
private TextBox textBox1 = new TextBox();

private void addButton_Click(object sender, System.EventArgs e)
{
	this.Controls.Add(textBox1);
}

Control.ControlCollection.Clear

  • 컬랙션의 모든 컨트롤을 제거한다.
panel1.Controls.Clear();

Control.ControlCollection.Contains(Control)

  • 해당 컬렉션이 포함되어 있는지 확인한다.
  • Bool 값 리턴
   if(panel1.Controls.Contains(removeButton))
   {
      panel1.Controls.Remove(removeButton);
   }
Control.Contains VS Control.Controls.Contains
1. Control.Contains : 직접 맞닿아 있는 경우 true 를 리턴한다.
2. Control.Controls.Contains : 계층구조 내부에 포함되어이 있는경우 (전부 탐색) true 를 리턴한다.

Control.ControlCollection.Find(String, Boolean)

public Control[] Find(string key, bool searchAllChildren);
  • key: 검색하려는 컨트롤의 이름.
  • searchAllChildren: 모든 하위 컨트롤을 재귀적으로 검색할지 또는 즉시 하위 컨트롤 중에서만 검색할지를 결정하는 bool 값
Control[] foundControls = this.Controls.Find("textBox1", true);

if (foundControls.Length > 0)
{
  TextBox textBox = foundControls[0] as TextBox;
  if (textBox != null)
  {
    // Do something with the found control
    textBox.Text = "Control found!";
  }
}
Label lbl = this.Controls.Find((label1), true).FirstOrDefault() as Label

Control.ControlCollection.Remove(Control)

  • 컬렉션의 특정 컨트롤을 제거한다.
panel1.Controls.Remove(removeButton);

Reference

 

Control.ControlCollection Class (System.Windows.Forms)

Represents a collection of Control objects.

learn.microsoft.com


There might be incorrect information or outdated content.