使用拖放重新排序winforms列表框?

Gar*_*son 37 c# listbox winforms

这是一个简单的过程吗?

我只是为内部工具编写一个快速的hacky UI.

我不想花一个年龄.

BFr*_*ree 81

这是一个快速下降和肮脏的应用程序.基本上我用一个按钮和一个ListBox创建了一个Form.单击按钮时,ListBox将填充接下来20天的日期(必须使用仅用于测试的内容).然后,它允许在ListBox中拖放以进行重新排序:

    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)
        {
            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 = e.Data.GetData(typeof(DateTime));
            this.listBox1.Items.Remove(data);
            this.listBox1.Items.Insert(index, data);
        }
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你.有两个(非常小的)陷阱.在_MouseDown中,选择在事件被触发之前不会切换,因此您需要调用IndexFromPoint来获取当前选择(并检查-1表示列表底部的含义).这里虽然X和Y已经是客户端坐标,所以你不要调用PointToClient在_DragDrop中你还需要检查索引是否为-1表示从列表的底部掉下来并忽略掉落或将项目移到底部你认为合适的清单.除了这两件事之外,这正是我追求的简单解决方案. (6认同)
  • 也喜欢这个小代码示例.发现与Gareth相同的错误并编辑了解决方法,希望将其删除. (4认同)

Wal*_*odz 8

迟了7年。但是对于任何新手来说,这里是代码。

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);
    }

    private void itemcreator_Load(object sender, EventArgs e)
    {
        this.listBox1.AllowDrop = true;
    }
Run Code Online (Sandbox Code Playgroud)