Reorder Listbox with Drag and Drop

Asked

Viewed 37 times

1

Good morning friends! I have a Listbox in my application C# Windows Form. I’d like a way to use the events Drag-n-Drop for reorder the items within the listbox the way the user wants it. Basically I would like to drag a line from the listbox to another destination line within the same listbox, reordering them.

EDIT: I don’t have many ideas of how to do it, I haven’t worked with drag and drop yet, but through examples on the Internet I’ve been building my code. Doesn’t work.

EDIT2: Code updated and working!

using System;
using System.Drawing;
using System.Windows.Forms;
namespace projetodetestes
{
    public partial class testedragdrop : Form
    {
        public testedragdrop()
        {
            InitializeComponent();
        }

        private void testedragdrop_Load(object sender, EventArgs e)
        {
            listBox1.AllowDrop = true;
        }

        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.listBox1.SelectedItem == null) return;
            this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Move);
        }

        private void listBox1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void listBox1_DragDrop(object sender, DragEventArgs e)
        {
            Point point = listBox1.PointToClient(new Point(e.X, e.Y));
            int index = this.listBox1.IndexFromPoint(point);
            if (index < 0) index = this.listBox1.Items.Count - 1;
            object data = listBox1.SelectedItem;
            this.listBox1.Items.Remove(data);
            this.listBox1.Items.Insert(index, data);
        }
    }
}
  • Show what you’ve done and present a [MCVE]...

1 answer

2

Probably the error is on the line:

object data = listBox1.SelectedItem;

Change to:

object data = e.Data.GetData(typeof(string)); 
//Caso não seja string altere, no meu caso é string
  • good morning buddy, tried to change that line and still doesn’t work.

  • I don’t know what kind of items in your ListBox, but change to the correct type that will work. In my ListBox insert the items a, b, c and d and worked with the string.

  • 1

    It’s working! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.