Drag and Drop between 2 list boxes

后端 未结 3 1376
难免孤独
难免孤独 2021-01-07 04:22

Trying to implement drag and drop between 2 listboxes and all examples I\'ve seen so far don\'t really smell good.

Can someone point me to or show me a good impleme

相关标签:
3条回答
  • 2021-01-07 04:37

    the proper way to do a drag-drop control in .net is by running code in the 2nd control's DragDrop event handler.

    It may "smell" weird, but this is how it works in .NET.

    0 讨论(0)
  • 2021-01-07 04:52

    Google gave this: http://www.codeproject.com/KB/dotnet/csdragndrop01.aspx

    It seems a pretty reasonable tutorial. If it smells bad, I think that's more to do with the API for drag and drop being awkward to use rather than the tutorial itself being poor.

    0 讨论(0)
  • 2021-01-07 04:57

    Here's a sample form. Get started with a new WF project and drop two list boxes on the form. Make the code look like this:

      public partial class Form1 : Form {
        public Form1() {
          InitializeComponent();
          listBox1.Items.AddRange(new object[] { "one", "two", "three" });
          listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);
          listBox1.MouseMove += new MouseEventHandler(listBox1_MouseMove);
          listBox2.AllowDrop = true;
          listBox2.DragEnter += new DragEventHandler(listBox2_DragEnter);
          listBox2.DragDrop += new DragEventHandler(listBox2_DragDrop);
        }
    
        private Point mDownPos;
        void listBox1_MouseDown(object sender, MouseEventArgs e) {
          mDownPos = e.Location;
        }
        void listBox1_MouseMove(object sender, MouseEventArgs e) {
          if (e.Button != MouseButtons.Left) return;
          int index = listBox1.IndexFromPoint(e.Location);
          if (index < 0) return;
          if (Math.Abs(e.X - mDownPos.X) >= SystemInformation.DragSize.Width ||
              Math.Abs(e.Y - mDownPos.Y) >= SystemInformation.DragSize.Height)
            DoDragDrop(new DragObject(listBox1, listBox1.Items[index]), DragDropEffects.Move);
        }
    
        void listBox2_DragEnter(object sender, DragEventArgs e) {
          DragObject obj = e.Data.GetData(typeof(DragObject)) as DragObject;
          if (obj != null && obj.source != listBox2) e.Effect = e.AllowedEffect;
        }
        void listBox2_DragDrop(object sender, DragEventArgs e) {
          DragObject obj = e.Data.GetData(typeof(DragObject)) as DragObject;
          listBox2.Items.Add(obj.item);
          obj.source.Items.Remove(obj.item);
        }
    
        private class DragObject {
          public ListBox source;
          public object item;
          public DragObject(ListBox box, object data) { source = box; item = data; }
        }
      }
    
    0 讨论(0)
提交回复
热议问题