hongyuniu

Whatever You Do, Do Your Best !

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1. 功能

  鼠标点击行首拖动换行

  多行选择删除

2. 主要代码

  

View Code
        private void dgv_SelectionChanged(object sender, EventArgs e)
        {
            
if (dgv.Rows.Count > 0 && selectionIdx > -1 && selectionIdx < dgv.Rows.Count - 1)// (dgv.SelectedRows.Count > 0))
            {

                
if (dgv.Rows.Count <= selectionIdx)
                    selectionIdx 
= dgv.Rows.Count - 1;
                dgv.Rows[selectionIdx].Selected 
= true;
                
//dgv.CurrentCell = dgv.Rows[selectionIdx].Cells[0];
            }
        }

        
private void dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            
if (e.RowIndex >= 0)
                selectionIdx 
= e.RowIndex;
        }

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

        
private void dgv_DragDrop(object sender, DragEventArgs e)
        {
            
int idx = GetRowFromPoint(e.X, e.Y);
            
if (idx < 0return;

            
if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
            {
                DataGridViewRow row 
= (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));
                DataRow ddr 
= ((DataRowView)row.DataBoundItem).Row;
                DataRow nr 
= ((DataTable)dgv.DataSource).NewRow();

                
for (int i = 0; i < row.Cells.Count; i++)
                {
                    nr[i] 
= row.Cells[i].Value;
                }
                selectionIdx 
= idx;
                ((DataTable)dgv.DataSource).Rows.InsertAt(nr, idx);
                ((DataTable)dgv.DataSource).Rows.Remove(ddr);
                dgv.ClearSelection();
            }
        }

        
private void dgv_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect 
= DragDropEffects.Move;
        }

        
private int GetRowFromPoint(int x, int y)
        {
            
for (int i = 0; i < dgv.RowCount; i++)
            {
                Rectangle rec 
= dgv.GetRowDisplayRectangle(i, false);

                
if (dgv.RectangleToScreen(rec).Contains(x, y))
                    
return i;
            }

            
return -1;
        }

  源码下载

posted on 2011-06-16 16:45  CsharpFish  阅读(2631)  评论(1编辑  收藏  举报