WinForm ListBox上下移动选中项(扩展)


一直都在做asp.net 的东西,WinForm 好久没碰过了,近乎陌生。今天同事说他的Winform 中的ListBox 无法上下移动项,让我感觉好奇怪,怎么可能,不就是交替选项么,换换位置应该就可以搞定。看了同事的代码,只觉得一片混沌,实在不忍心再读下去,就自己操刀写一下了。(下面的代码使用了扩展方法,需要编译器版本>=3.0 ,也可以根据相关语法自行修改成2.0 以下的版本)

  代码功能 :比较简单,就是当选中ListBox 中的项的时候,点击上移按钮,项向上移动,点击下移按钮,项向下移动。

  [ 使用:建立cs 文件,并COPY 以下代码置于其中,即可按照示例所用的方式进行使用了]

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("请选择"); 
       }); 
     }

  怎么样,代码是不是足够简洁和优雅?基本上可以达到预期的效果了,大家可以根据自己的需求稍做修改。有任何问题和疑问可以留言告诉我!


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3