/* 首先设置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; // 记下拖动源数据行的索引及已鼠标按下坐标为中心的
DataGridView的拖拽换行功能
最新推荐文章于 2024-05-16 10:02:34 发布
本文介绍了如何在Windows Forms应用程序中实现DataGridView控件的拖拽换行功能。通过设置AllowDrop、MultiSelect和SelectionMode属性,结合Mouse事件处理,实现在DataGridView中拖动行并调整顺序。拖放过程中使用了BinaryFormatter进行对象序列化和反序列化,以在拖放操作中传递数据。
摘要由CSDN通过智能技术生成