DataGridView的拖拽换行功能

本文介绍了如何在Windows Forms应用程序中实现DataGridView控件的拖拽换行功能。通过设置AllowDrop、MultiSelect和SelectionMode属性,结合Mouse事件处理,实现在DataGridView中拖动行并调整顺序。拖放过程中使用了BinaryFormatter进行对象序列化和反序列化,以在拖放操作中传递数据。
摘要由CSDN通过智能技术生成
/*
  首先设置DataGridView控件的AllowDrop属性为True,MultiSelect为False,SelectionMode为FullRowSelect 
 */
namespace DragRow
{
    public partial class MainForm : Form
    {
        public BindingList<Employee> EmployeeList;
        
        // 拖动的源数据行索引
        private int indexOfItemUnderMouseToDrag = -1;
        // 拖动的目标数据行索引
        private int indexOfItemUnderMouseToDrop = -1;
        // 拖动中的鼠标所在位置的当前行索引
        private int indexOfItemUnderMouseOver = -1;
        // 不启用拖放的鼠标范围
        private Rectangle dragBoxFromMouseDown = Rectangle.Empty;

        public MainForm()
        {
            InitializeComponent();            
        }
              
        private void MainForm_Load(object sender, EventArgs e)
        {
            EmployeeList = new BindingList<Employee>();
            EmployeeList.ListChanged += new ListChangedEventHandler(EmployeeList_ListChanged);

            List<Employee> empList = Employee.GetEmployeeList();
         
            foreach (var item in empList)
            {
                EmployeeList.Add(item);
            }
            dataGridView.DataSource = EmployeeList;
        }

        //为的是No列始终是重新排列的
        void EmployeeList_ListChanged(object sender, ListChangedEventArgs e)
        {
            int index = 1;
            foreach (var item in this.EmployeeList)
            {
                item.No = index++;
            }
        }

        private void dataGridView_MouseDown(object sender, MouseEventArgs e)
        {
            // 通过鼠标按下的位置获取所在行的信息
            var hitTest = dataGridView.HitTest(e.X, e.Y);
            if (hitTest.Type != DataGridViewHitTestType.Cell)
                return;

            // 记下拖动源数据行的索引及已鼠标按下坐标为中心的
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值