实现ListBox控件选中项上下移动重新排序功能
效果图:
移动后效果:
代码:
/// <summary> /// 上移选中项 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //http://www.cnblogs.com/babycool 酷小孩 //获取集合中项的数量 int lbxlength = this.listBox1.Items.Count; //选中项的索引 int isselected = this.listBox1.SelectedIndex; if (lbxlength > isselected && isselected > 0) { object SelectItem = this.listBox1.SelectedItem; this.listBox1.Items.RemoveAt(isselected); this.listBox1.Items.Insert(isselected - 1, SelectItem); this.listBox1.SelectedIndex = isselected - 1; } } /// <summary> /// 下移选中项 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { int lbxlength = this.listBox1.Items.Count; int isselected = this.listBox1.SelectedIndex; if (lbxlength > isselected && isselected < lbxlength - 1) { object selectItem = this.listBox1.SelectedItem; this.listBox1.Items.RemoveAt(isselected); this.listBox1.Items.Insert(isselected + 1, selectItem); this.listBox1.SelectedIndex = isselected + 1; } } //遍历每一项 private void button3_Click(object sender, EventArgs e) { int count = listBox1.Items.Count; for (int i = 0; i < count; i++) { MessageBox.Show(listBox1.Items[i].ToString()); } }
转载请注明出处。