ListView选中selectedItem上下移动

     // 向上
         private   void  button1_Click( object  sender, EventArgs e)
        {
            
if  ( this .listView1.SelectedItems.Count  ==   0 )
            {
                
return ;
            }

            listView1.BeginUpdate();

            
if  ( this .listView1.SelectedItems[ 0 ].Index  >   0 )
            {
                
foreach  (ListViewItem var  in  listView1.SelectedItems)
                {
                    ListViewItem item 
=  var;
                    
int  indexSelectedItem  =  var.Index;
                    listView1.Items.RemoveAt(indexSelectedItem);
                    listView1.Items.Insert(indexSelectedItem 
-   1 , item);
                }
            }
            listView1.EndUpdate();

            
if (listView1.Items.Count  > 0   &&  listView1.SelectedItems.Count  > 0 )
            {
                listView1.Focus();
                listView1.SelectedItems[
0 ].Focused  =   true ;
                listView1.SelectedItems[
0 ].EnsureVisible();
            }
        }
        
// 向下
         private   void  button2_Click( object  sender, EventArgs e)
        {
            
if  ( this .listView1.SelectedItems.Count  ==   0 )
            {
                
return ;
            }
            
this .listView1.BeginUpdate();
            
int  indexMaxSelectedItem  =  listView1.SelectedItems[listView1.SelectedItems.Count  -   1 ].Index;

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

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


你可能感兴趣的:(ListView)