C# ListBox中的Item拖拽代码分享

时间:2021-09-11 07:41:06

我们先来看下运行效果图

C# ListBox中的Item拖拽代码分享

form1.cs代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;
using system.collections;
 
namespace moveitem
{
  public partial class form1 : form
  {
    public form1()
    {
      initializecomponent();
    }
    arraylist list = new arraylist();
    private void listbox1_selectedindexchanged(object sender, eventargs e)
    {
 
    }
 
    private void form1_load(object sender, eventargs e)
    {
      for (int i = 1; i <= 10; i++)
      {
        list.add(i);
        string s = i.tostring();
        listbox1.items.add(s);
      }
 
    }
 
    private void listbox2_selectedindexchanged(object sender, eventargs e)
    {
      
    }
 
    private void button1_click(object sender, eventargs e)
    {
      //单选,无法实现多选
      //string str = this.listbox1.text.trim().tostring();
      //if (listbox1.items.contains(str))
      //{
      //  listbox1.items.remove(str);
      //  listbox2.items.add(str);
      //}
      for (int i=0;i<listbox1.selectedindices.count;i++)
      {
        listbox2.items.add(listbox1.items[listbox1.selectedindices[i]]);
        listbox1.items.removeat(listbox1.selectedindices[i]);
        i--;
      }
    }
 
    private void button2_click(object sender, eventargs e)
    {
      for (int i = 0; i < listbox2.selectedindices.count; i++)
      {
        listbox1.items.add(listbox2.items[listbox2.selectedindices[i]]);
        listbox2.items.removeat(listbox2.selectedindices[i]);
        i--;
      }
    }
 
    private void button3_click(object sender, eventargs e)
    {
      listbox2.items.addrange(listbox1.items);
      listbox1.items.clear();
    }
 
    private void button4_click(object sender, eventargs e)
    {
      listbox1.items.addrange(listbox2.items);
      listbox2.items.clear();
    }
  }
}

大家可以测试运行下,有其他问题可以在下方的留言区讨论,感谢大家对服务器之家的支持。

原文链接:https://www.idaobin.com/archives/967.html