winform拖动排序

近日,项目中有用到拖动排序的功能,一时没有思路,问了N个朋友,终于在一个朋友的帮助下搞定了这个排序。代码很简单也没加注释,自己看吧。

创建一个组件类(项目上右键->添加->组件),用户控件神马的都行

这里以一个Label为例

代码正文:

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class DragabledLabel : Label
    {
        private Point mouse_offse;
        private bool bDraged = false;
        private int xPos;

        public DragabledLabel()
        {
            InitializeComponent();
        }

        public DragabledLabel(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            bDraged = true;
            this.BringToFront();
            this.BackColor = Color.Beige;
            xPos = this.Location.X;
            mouse_offse = new Point(-e.X, -e.Y);
            //base.OnMouseDown(e);
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (bDraged)
            {
                Point mousePos = Control.MousePosition;
                mousePos.Offset(mouse_offse.X, mouse_offse.Y);
                this.Location = this.Parent.PointToClient(mousePos);
            }
            //base.OnMouseMove(e);
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                Point mousePos = Control.MousePosition;
                mousePos.Offset(mouse_offse.X, mouse_offse.Y);
                this.Location = this.Parent.PointToClient(mousePos);
                this.BackColor = SystemColors.Control;
                bDraged = false;
            }
            Sort();
            //base.OnMouseUp(e);
        }

        private void Sort()
        {
            ControlCollection DragabledLabels = this.Parent.Controls;
            Control parent = this.Parent;
            List<Control> list = new List<Control>();
            while (DragabledLabels.Count > 0)
            {
                list.Add(GetMinYControl(DragabledLabels));
            }
            for (int index = 0; index < list.Count; index++)
            {
                list[index].Location = new Point(0, 20 * index);
                parent.Controls.Add(list[index]);
            }
        }

        private Control GetMinYControl(ControlCollection cc)
        {
            Control c = cc[0];
            if (cc.Count == 1)
            {
                cc.Remove(c);
                return c;
            }

            for (int i = 1; i < cc.Count; i++)
            {
                if (cc[i].Location.Y < c.Location.Y)
                {
                    c = cc[i];
                }
            }
            cc.Remove(c);
            return c;
        }
    }
}

点击查看原图点击查看原图 

 

嗯,完成。在工具箱里找到这个组件,拖到窗体中就可以用

见附件:Winform拖动排序Demo

上一篇‡: C#PANEL跨越滚动条截图

下一篇‡: 统计数据库中表,视图,存储过程个数的SQL

最近回复