疏林如画

导航

【代码保留】WinForm ListBox上下移动选中项(扩展)

【代码保留】WinForm ListBox上下移动选中项(扩展)

public static class ListBoxExtension
{
    public static bool MoveSelectedItems(this ListBox listBox, bool isUp, Action noSelectAction)
    {
        if (listBox.SelectedItems.Count > 0)
        {
            return listBox.MoveSelectedItems(isUp);
        }
        else
        {
            noSelectAction();
            return false;
        }
    }

    public static bool MoveSelectedItems(this ListBox listBox, bool isUp)
    {
        bool result = true;
        ListBox.SelectedIndexCollection indices = listBox.SelectedIndices;
        if (isUp)
        {
            if (listBox.SelectedItems.Count > 0 && indices[0] != 0)
            {
                foreach (int i in indices)
                {
                    result &= MoveSelectedItem(listBox, i, true);
                }
            }
        }
        else
        {
            if (listBox.SelectedItems.Count > 0 && indices[indices.Count - 1] != listBox.Items.Count - 1)
            {
                for (int i = indices.Count - 1; i >= 0; i--)
                {
                    result &= MoveSelectedItem(listBox, indices[i], false);
                }
            }
        }
        return result;
    }

    public static bool MoveSelectedItem(this ListBox listBox, bool isUp, Action noSelectAction)
    {
        if (listBox.SelectedItems.Count > 0)
        {
            return MoveSelectedItem(listBox, listBox.SelectedIndex, isUp);
        }
        else
        {
            noSelectAction();
            return false;
        }
    }

    public static bool MoveSelectedItem(this ListBox listBox, bool isUp)
    {
        return MoveSelectedItem(listBox, listBox.SelectedIndex, isUp);
    }

    private static bool MoveSelectedItem(this ListBox listBox, int selectedIndex, bool isUp)
    {
        if (selectedIndex != (isUp ? 0 : listBox.Items.Count - 1))
        {
            object current = listBox.Items[selectedIndex];
            int insertAt = selectedIndex + (isUp ? -1 : 1);

            listBox.Items.RemoveAt(selectedIndex);
            listBox.Items.Insert(insertAt, current);
            listBox.SelectedIndex = insertAt;
            return true;
        }
        return false;
    }
}

private void btnUp_Click(object sender, EventArgs e)
        {
            this.listBox1.MoveSelectedItems(true, () => {
                MessageBox.Show("请选择");
            });
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            this.listBox1.MoveSelectedItems(false, () => {
                MessageBox.Show("请选择");
            });
        }

posted on 2012-01-14 14:56  疏林如画  阅读(835)  评论(0编辑  收藏  举报