Drag and Drop Between Two Lists

Trying to implement drag and drop between two lists and all the examples I've seen so far doesn't actually smell very good.

Can someone point me or show me a good implementation?

+3
source share
4 answers

Have you seen this one ?

+3
source

Here is a sample form. Get started with the new WF project and leave two lists in the form. Make the code 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; }
    }
  }
+8
source

.net - DragDrop.

"" , .NET.

+1

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

Seems like a pretty reasonable tutorial. If it smells bad, I think that more to do with the drag and drop API is awkward to use, rather than the tutorial itself was poor.

+1
source

Source: https://habr.com/ru/post/1724333/


All Articles