2009-09-01 4 views
2

컨트롤의 다음 형제 및 이전 형제를 찾는 좋은 방법은 무엇입니까?C# : 다음 및 이전 형제 컨트롤을 찾는 좋은 방법

예를 들어 버튼, 텍스트 상자 등이 포함 된 패널이있는 경우입니다. 그 중에는 텍스트 상자와 버튼으로 구성된 사용자 정의 컨트롤이 있습니다. 버튼을 클릭하면 예를 들어이 사용자 컨트롤 뒤에 오는 컨트롤의 이름을 찾고 싶습니다.

나의 목표는 그 위치의 앞뒤에 위치를 바꿀 수있는 사용자 정의 컨트롤을 만드는 것입니다 (코스가있는 경우). 당신이 Controls.GetChildIndex (제어)를 호출 할 수 있습니다처럼

내가이 가지 사소한해야 알아,하지만 난 그냥이 하나의 주위에 내 머리를 정리하고 수없는 것 ... =/

+0

"다음"과 "이전"을 어떻게 정의합니까? 탭 순서? 컨테이너에 추가되는 순서? 위치 기반? –

+0

부모의 Controls 컬렉션에있는 순서입니다. 시각적으로,이 경우 흐름 패널에서 컨트롤의 앞이나 뒤에 오는 컨트롤입니다. – Svish

답변

1

이 해결 방법은 FlowLayoutPanel 경우에만 사용됩니다.

private enum Direction 
{ 
    Next, 
    Previous 
} 

private void SwapLocations(Control current, Direction direction) 
{ 
    if (current == null) 
    { 
     throw new ArgumentNullException("current"); 
    } 
    // get the parent 
    Control parent = current.Parent; 
    // forward or backward? 
    bool forward = direction == Direction.Next; 
    // get the next control in the given direction 
    Control next = parent.GetNextControl(current, forward); 
    if (next == null) 
    { 
     // we get here, at the "end" in the given direction; we want to 
     // go to the other "end" 
     next = current; 
     while (parent.GetNextControl(next, !forward) != null) 
     { 
      next = parent.GetNextControl(next, !forward); 
     } 
    } 
    // get the indices for the current and next controls 
    int nextIndex = parent.Controls.IndexOf(next); 
    int currentIndex = parent.Controls.IndexOf(current); 

    // swap the indices 
    parent.Controls.SetChildIndex(current, nextIndex); 
    parent.Controls.SetChildIndex(next, currentIndex); 
} 

사용 예 : 그들이 Controls 컬렉션에 나타난 순서대로 컨트롤을 낳는 때문에, 트릭은 위치를 교환해야 컨트롤의 인덱스를 발견하고이를 전환하는 과정이다

private void Button_Click(object sender, EventArgs e) 
{ 
    SwapLocations(sender as Control, Direction.Next); 
} 
1

같습니다 현재 컨트롤을 사용하여 인덱스를 가져온 다음 Controls 컬렉션으로 색인하여 이전 형제와 다음 형제를 가져옵니다.

+0

예제를 제공해 주시겠습니까? 가급적 첫 번째 또는 마지막 컨트롤 일 수도 있고 아닐 수도 있다는 점을 고려해야합니다. – Svish

0
this.GetNextControl(Control,bool forward); 

하위 컨트롤의 탭 순서에서 앞뒤로 다음 컨트롤을 검색합니다.

편집 :

컨트롤 컬렉션 및 그 방법.

+0

Doh ... 어떻게 그 중 하나를 그리워 ...하지만, 컨트롤 컬렉션에서 컨트롤을 재정렬 할 때 탭 순서가 동일하게 유지됩니까? 아니면 그에 따라 변경됩니까? – Svish

-2
this.Controls.SetChildIndex(panelContainerOfHeaderAndUserControl1, 0); 
this.Controls.SetChildIndex(panelContainerOfHeaderAndUserControl, 1); 

나를 위해 일했다. 런타임에 작성된 패널이 두 개 있지만 스타일이 채워진 패널과 다른 패널이 있습니다. 채우기 스타일이있는 패널은 위쪽 패널과 겹쳐집니다.

컨트롤의 형제 순서를 설정하면 해당 컨트롤이 수정됩니다.

관련 문제