개발/C#
Listbox에서 아이템을 위/아래로 이동하는 함수
다물칸
2024. 2. 6. 14:22
728x90
반응형
위/아래 이동은 버튼을 추가했다고 가정한다.
DevExpress의 ListBoxControl도 동일하게 동작가능하다.
아래 코에서 ListBox를 ListBoxControl로 수정해서 사용하면 된다.
public static class ListBoxExtension
{
public static void MoveSelectedItemUp(this ListBox listBox)
{
_MoveSelectedItem(listBox, -1);
}
public static void MoveSelectedItemDown(this ListBox listBox)
{
_MoveSelectedItem(listBox, 1);
}
static void _MoveSelectedItem(ListBox listBox, int direction)
{
// Checking selected item
if (listBox.SelectedItem == null || listBox.SelectedIndex < 0)
return; // No selected item - nothing to do
// Calculate new index using move direction
int newIndex = listBox.SelectedIndex + direction;
// Checking bounds of the range
if (newIndex < 0 || newIndex >= listBox.Items.Count)
return; // Index out of range - nothing to do
object selected = listBox.SelectedItem;
// Save checked state if it is applicable
//var checkedListBox = listBox as CheckedListBox;
//var checkState = CheckState.Unchecked;
//if (checkedListBox != null)
// checkState = checkedListBox.GetItemCheckState(checkedListBox.SelectedIndex);
// Removing removable element
listBox.Items.Remove(selected);
// Insert it in new position
listBox.Items.Insert(newIndex, selected);
// Restore selection
listBox.SetSelected(newIndex, true);
// Restore checked state if it is applicable
//if (checkedListBox != null)
// checkedListBox.SetItemCheckState(newIndex, checkState);
}
}
출처: StackOverflow
반응형