2013-06-23 2 views
1

CheckedListBox에 두 항목의 위치를 ​​바꾸는 확장 메서드를 만들었습니다. 이 메서드는 정적 유틸리티 클래스에 저장됩니다. 문제는 CheckState가 이동하지 않는다는 것입니다. 체크 된 항목을 목록에서 위로 이동하면 체크 상자 상태가 유지되고 이동 된 항목이 해당 항목에서 CheckState를 인계합니다.항목 가져 오기 정적 메서드로 CheckState

내 코드는 다음과 같습니다

public static System.Windows.Forms.CheckedListBox.ObjectCollection Swap(this System.Windows.Forms.CheckedListBox.ObjectCollection lstBoxItems, int indexA, int indexB) 
{ 
    if (indexB > -1 && indexB < lstBoxItems.Count - 1) 
    { 
     object tmpItem = lstBoxItems[indexA];   
     lstBoxItems[indexA] = lstBoxItems[indexB]; 
     lstBoxItems[indexB] = tmpItem; 
    } 
    return lstBoxItems; 
} 

(분명히 작동하지 않습니다)이 같은

public static System.Windows.Forms.CheckedListBox.ObjectCollection Swap(this System.Windows.Forms.CheckedListBox.ObjectCollection lstBoxItems, int indexA, int indexB) 
{ 
    if (indexB > -1 && indexB < lstBoxItems.Count - 1) 
    { 
     object tmpItem = lstBoxItems[indexA]; 
     System.Windows.Forms.CheckState state = tmpItem.CheckState; 

     lstBoxItems[indexA] = lstBoxItems[indexB]; 
     lstBoxItems[indexB] = tmpItem; 
    } 
    return lstBoxItems; 
} 

코드는 단순히이

myCheckedListBox.Items.Swap(selectedIndex, targetIndex); 
처럼라고는 내가 원하는입니다

답변

3

전에 CheckedListBox을 사용하지 않았지만 MSDN 문서를보고 추측 할 위험이 있다면 그것 때문에 나는 GetItemCheckedStateSetItemCheckedState 방법을 사용하고 싶다고 말하고 싶습니다. 그러나 이는 또한 .ItemsObjectCollection이 아닌 CheckedListBox을 전달해야 함을 의미합니다.

public static System.Windows.Forms.CheckedListBox Swap(this System.Windows.Forms.CheckedListBox listBox, int indexA, int indexB) 
{ 
    var lstBoxItems = listBox.Items; 
    if (indexB > -1 && indexB < lstBoxItems.Count - 1) 
    { 
     System.Windows.Forms.CheckState stateA = listBox.GetItemCheckState(indexA); 
     System.Windows.Forms.CheckState stateB = listBox.GetItemCheckState(indexB); 

     object tmpItem = lstBoxItems[indexA]; 
     lstBoxItems[indexA] = lstBoxItems[indexB]; 
     lstBoxItems[indexB] = tmpItem; 

     listBox.SetItemCheckState(indexA, stateB); 
     listBox.SetItemCheckState(indexB, stateA); 
    } 
    return listBox; 
} 

그래서 자연스럽게 호출 코드는 다음과 같이 변경합니다 :

myCheckedListBox.Swap(selectedIndex, targetIndex); 

또한, 내 방법은 ObjectCollection 대신뿐만 아니라 입력 CheckedListBox을 반환합니다; 서명 된 매개 변수의 변경을 고려할 때 이것이 더 적절할 것이라고 생각했습니다.

+0

감사합니다. 솔루션을보기 전에 몇 분만에 문제를 풀었습니다. 동일한 변수 이름과 구문을 사용했습니다 :-). 확인을위한 Thx! 그것을 upvote 받아들입니다. – Christoffer

1

아마도 문제는 복사본 대신 실제 목록 상자 항목의 현재 검사 상태를 가져와야한다는 것입니다. 목록 상자가 항목 목록 내용과 별도로 수표를 관리하고 있다는 것을 이미 알고 있습니다!

또한 항목 A와 B에 대해 현재 체크 된 상태를 가져와야합니다. 항목 스왑을 수행 한 후 체크 된 상태를 두 항목에 다시 적용하여 두 스왑 된 항목의 상태를 유지 관리합니다.

+0

그게 좋은 소식입니다. 그것은 실제로 나에게 또 다른 문제를 해결했다. 목록에서 업데이트 된 목록을 가져 오는 프로필이 있습니다. 귀하의 솔루션을 사용하면 프로파일에서 체크리스트를 얻는 모든 단일 목록 항목을 처리 할 필요가 없습니다. – Christoffer

관련 문제