C#实现DataGridView到DataGridView的拖拽

转载自:https://www.cnblogs.com/michaelxu/archive/2009/09/27/1574905.html

将一个DataGridView中的某一行拖拽到另一个DataGridView中。实现从gridSource到gridTarget的拖拽,需要一个设置和三个事件:

1、设置gridTarget的属性AllowDrop为True
2、实现gridSource的MouseDown事件,在这里进行要拖拽的Cell内容的保存,保存到剪贴板。
3、实现gridTarget的DragDrop和DragEnter事件,DragDrop事件中的一个难点就是决定拖拽到哪一个Cell

代码如下:

gridSource的MouseDown事件:

 1 Code
 2 private void gridSource_MouseDown(object sender, MouseEventArgs e)
 3 {
 4      if (e.Button == MouseButtons.Left)
 5      {
 6           DataGridView.HitTestInfo info = this.gridSource.HitTest(e.X, e.Y);
 7           if (info.RowIndex >= 0)
 8           {
 9               if (info.RowIndex >= 0 && info.ColumnIndex >= 0)
10               {
11                   string text = (String)this.gridSource.Rows[info.RowIndex].Cells[info.ColumnIndex].Value;
12                    if (text != null)
13                     {
14                         this.gridSource.DoDragDrop(text, DragDropEffects.Copy);
15                      }
16                }
17            }
18        }
19  }
View Code

gridTarget的DragDrop事件:

 1 Code
 2 private void gridTarget_DragDrop(object sender, DragEventArgs e)
 3 {
 4        //得到要拖拽到的位置
 5      Point p = this.gridTarget.PointToClient(new Point(e.X, e.Y));
 6       DataGridView.HitTestInfo hit = this.gridTarget.HitTest(p.X, p.Y);
 7       if (hit.Type == DataGridViewHitTestType.Cell)
 8       {
 9             DataGridViewCell clickedCell = this.gridTarget.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
10             clickedCell.Value = (System.String)e.Data.GetData(typeof(System.String));
11        //如果只想允许拖拽到某一个特定列,比如Target Field Expression,则先要判断列是否为Target Field Expression,如下:
12              //if (0 == string.Compare(clickedCell.OwningColumn.Name, "Target Field Expression"))
13              //{
14              //    clickedCell.Value = (System.String)e.Data.GetData(typeof(System.String));
15              //}
16        }
17 }
View Code

gridTarget的DragEnter事件:

private void gridTarget_DragEnter(object sender, DragEventArgs e)
{
     e.Effect = DragDropEffects.Copy;
}
原文地址:https://www.cnblogs.com/BennyHua/p/11149366.html