zoukankan      html  css  js  c++  java
  • 实现DataGridView行的拖动,即实现行的顺序交换

    参考:http://blog.csdn.net/soarheaven/article/details/3267379

    1.界面准备
    (1)首先在form中添加一个DataGridView控件,将默认AllowDrop=false 的属性设置为True,否侧不能拖动!
    (2)对DataGridView的对象实现非数据源的绑定,因为设置DataSource属性即当控件被数据绑定时,无法以编程方式向 DataGridView 的行集合中添加行。
     
     
    2.代码准备
    (1)控制移动时鼠标的图形,否则是一个禁止移动的标识
            private void dataGridView1_DragEnter(object sender, DragEventArgs e)
    
            {
    
                e.Effect = DragDropEffects.Move;
    
            }

     (2)控制拖动的条件,也可以自行放宽条件

            private void  dataGridView1 _CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
    
            {
    
                if ((e.Clicks < 2) && (e.Button == MouseButtons.Left))
    
                {
    
                    if ((e.ColumnIndex == -1) && (e.RowIndex > -1))
    
                        dataGridView1.DoDragDrop(dataGridView1.Rows[e.RowIndex], DragDropEffects.Move);
    
                }
    
            }

    (3)拖动后实现行的删除和添加,实现行交换位置的错觉

     
            int selectionIdx = 0;
    
            private void  dataGridView1_DragDrop(object sender, DragEventArgs e)
    
            {
    
                int idx = GetRowFromPoint(e.X, e.Y);
    
     
    
                if (idx < 0) return;
    
     
    
                if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
    
                {
    
                    DataGridViewRow row = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));
    
                    dataGridView1.Rows.Remove(row);
    
                    selectionIdx = idx;
    
                    dataGridView1.Rows.Insert(idx, row);
    
                }
    
            }
    
     
    
            private int GetRowFromPoint(int x, int y)
    
            {
    
                for (int i = 0; i < dataGridView1.RowCount; i++)
    
                {
    
                    Rectangle rec = dataGridView1.GetRowDisplayRectangle(i, false);
    
     
    
                    if (dataGridView1.RectangleToScreen(rec).Contains(x, y))
    
                        return i;
    
                }
    
     
    
                return -1;
    
            }

    (4)控制被移动的行始终是选中行

            private void kryptonDataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    
            {
    
                if (selectionIdx > -1)
    
                {
    
                    dataGridView1.Rows[selectionIdx].Selected = true;
    
                    dataGridView1.CurrentCell = dataGridView1.Rows[selectionIdx].Cells[0];
    
                }
    
            }
  • 相关阅读:
    ASP.NET的三层架构(DAL,BLL,UI)
    页面开发辅助类—HtmlHelper初步了解
    ASP MVC之参数传递
    ASP.NET MVC学习之母版页和自定义控件的使用
    ASP.Net MVC开发基础学习笔记(2):HtmlHelper与扩展方法
    UITableView动态改变Cell高度
    UITableView动态改变Cell高度
    nodejs豆瓣爬虫
    nodejs豆瓣爬虫
    苹果系统OSX中Automator批量重命名
  • 原文地址:https://www.cnblogs.com/swtool/p/5246518.html
Copyright © 2011-2022 走看看