views:

1780

answers:

3

Is this a simple process?

I'm only writing a quick hacky UI for an internal tool.

I don't want to spend an age on it.

A: 

The first time it takes a few hours if you never implemented drag and drop, want to get it done right and have to read through the docs. Especially the immediate feedback and restoring the list if the user cancels the operation require some thoughts. Encapsulating the behavior into a reusable user control will take some time, too.

If you have never done drag and drop at all, have a look at this drag and drop example from the MSDN. This would be a good starting point and it should take you maybe half a day to get the thing working.

Daniel Brückner
A: 

An alternative is using the list-view control, which is the control Explorer uses to display the contents of folders. It is more complicated, but implements item dragging for you.

Simon Buchan
+5  A: 

Here's a quick down and dirty app. Basically I created a Form with a button and a ListView. On button click, the listview gets populated with the date of the next 20 days (had to use something just for testing). Then, it allows drag and drop within the listview for reordering:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.listBox1.AllowDrop = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <= 20; i++)
            {
                this.listBox1.Items.Add(DateTime.Now.AddDays(i));
            }
        }

        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            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);
            object data = e.Data.GetData(typeof(DateTime));
            this.listBox1.Items.Remove(data);
            this.listBox1.Items.Insert(index, data);

        }
BFree
This was great thank you. There are two (very minor) gotchas.In _MouseDown, selection does not switch before the event is fired so you need to call IndexFromPoint to get the current selection (and check for -1 meaning off the bottom of the list). Here though, X and Y are already client coordinates so you don't call PointToClientIn _DragDrop you also need to check if index is -1 indicating dropping off the bottom of the list and either ignore the drop or move the item to the bottom of the list as you see fit.Those two things apart though, this is exactly the simple solution I was after.
Gareth Simpson