ListView選中selectedItem上下移動 C#

iDotNetSpace發表於2010-06-21

//上移

private void ListViewUpMove(ListView listView)
        {
            if (listView.SelectedItems.Count == 0)
            {
                return;
            }

            listView.BeginUpdate();
            if (listView.SelectedItems[0].Index > 0)
            {
                foreach (ListViewItem lvi in listView.SelectedItems)
                {
                    ListViewItem lviSelectedItem = lvi;
                    int indexSelectedItem = lvi.Index;
                    listView.Items.RemoveAt(indexSelectedItem);
                    listView.Items.Insert(indexSelectedItem - 1, lviSelectedItem);
                }
            }
            listView.EndUpdate();

            if (listView.Items.Count > 0 && listView.SelectedItems.Count > 0)
            {
                listView.Focus();
                listView.SelectedItems[0].Focused = true;
                listView.SelectedItems[0].EnsureVisible();
            }

        }

=============================================================

//下移
        private void ListViewDownMove(ListView listView)
        {
            if (listView.SelectedItems.Count == 0)
            {
                return;
            }

            listView.BeginUpdate();
            int indexMaxSelectedItem = listView.SelectedItems[listView.SelectedItems.Count - 1].Index;

            if (indexMaxSelectedItem < listView.Items.Count - 1)
            {
                for (int i = listView.SelectedItems.Count - 1; i >= 0; i--)
                {
                    ListViewItem lviSelectedItem = listView.SelectedItems[i];
                    int indexSelectedItem = lviSelectedItem.Index;
                    listView.Items.RemoveAt(indexSelectedItem);
                    listView.Items.Insert(indexSelectedItem + 1, lviSelectedItem);
                }
            }
            listView.EndUpdate();

            if (listView.Items.Count > 0 && listView.SelectedItems.Count > 0)
            {
                listView.Focus();
                listView.SelectedItems[listView.SelectedItems.Count - 1].Focused = true;
                listView.SelectedItems[listView.SelectedItems.Count - 1].EnsureVisible();
            }
        }

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-665756/,如需轉載,請註明出處,否則將追究法律責任。

相關文章