實現DataGridView行的拖動,即實現行的順序交換

來源:互聯網
上載者:User

標籤:datagridview   blog   c   tar   http   a   

參考:http://blog.csdn.net/soarheaven/article/details/32673791.介面準備(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];            }        }
相關關鍵詞:
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.