C# DataGridView 表格行(Row) 上下移動


https://blog.csdn.net/plato_2/article/details/17434715?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2.pc_relevant_default&utm_relevant_index=4

 

好像有用吧,但是太麻煩了

 

https://blog.csdn.net/xiaotaibai2008/article/details/8099348

 

(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];
            }
        }
————————————————
版權聲明:本文為CSDN博主「xiaotaibai2008」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/xiaotaibai2008/article/details/8099348

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM