728x90

listView 에서 선택된 행과 이전행/다음행의 값을 서로 맞바꾸는 코드이다.

선택된 행도 같이 변경되게 처리했다.


private void lineSwapPreviousToolStripMenuItem_Click(object sender, EventArgs e)
{
    listView_previousSwap(listView1);
}

private void lineSwapNextToolStripMenuItem_Click(object sender, EventArgs e)
{
    listView_nextSwap(listView1);
}

private void listView_previousSwap(ListView LV)
{
    if (LV.SelectedIndices.Count > 0 && LV.SelectedItems[0].Index > 0)
    {
        int index = LV.SelectedItems[0].Index;  // 선택된 행의 인덱스
        int previousindex = index - 1; // 이전행의 인덱스

        string temp2 = LV.Items[index].SubItems[2].Text;  // 선택된 행의 값을 임시변수에 저장
        LV.Items[index].SubItems[2].Text = LV.Items[previousindex].SubItems[2].Text;
        LV.Items[previousindex].SubItems[2].Text = temp2;

        string temp3 = LV.Items[index].SubItems[3].Text;
        LV.Items[index].SubItems[3].Text = LV.Items[previousindex].SubItems[3].Text;
        LV.Items[previousindex].SubItems[3].Text = temp3;

        string temp4 = LV.Items[index].SubItems[4].Text;
        LV.Items[index].SubItems[4].Text = LV.Items[previousindex].SubItems[4].Text;
        LV.Items[previousindex].SubItems[4].Text = temp4;


        listView_FocusedLine(LV, previousindex);

    }
}

private void listView_nextSwap(ListView LV)
{
    if (LV.SelectedIndices.Count > 0 && LV.SelectedItems[0].Index < LV.Items.Count -1)
    {
        int index = LV.SelectedItems[0].Index;  // 선택된 행의 인덱스
        int nextindex = index + 1; // 다음행의 인덱스

        string temp2 = LV.Items[index].SubItems[2].Text;  // 선택된 행의 값을 임시변수에 저장
        LV.Items[index].SubItems[2].Text = LV.Items[nextindex].SubItems[2].Text;
        LV.Items[nextindex].SubItems[2].Text = temp2;

        string temp3 = LV.Items[index].SubItems[3].Text;
        LV.Items[index].SubItems[3].Text = LV.Items[nextindex].SubItems[3].Text;
        LV.Items[nextindex].SubItems[3].Text = temp3;

        string temp4 = LV.Items[index].SubItems[4].Text;
        LV.Items[index].SubItems[4].Text = LV.Items[nextindex].SubItems[4].Text;
        LV.Items[nextindex].SubItems[4].Text = temp4;


        listView_FocusedLine(LV, nextindex);

    }
}


private void listView_FocusedLine(ListView LV, int index)
{
    if (index < 0 || index >= LV.Items.Count || LV.Items.Count == 0) return;
    LV.SelectedItems.Clear();
    LV.Items[index].Selected = true;
    LV.Items[index].EnsureVisible();
    LV.Items[index].Focused = true;
    LV.Focus();
}


블로그 이미지

Link2Me

,