I encountered a problem at work today. I needed to drag a row in a dview to another DataGridView. I searched it on the Internet. Most of them were dragged from the DataGridView to TextBox and other controls without dragging them
In the DataGridView. It is easy to drag to TextBox, but the question is: how to decide which Cell to drag to the dview?
After studying the problem for two hours, I finally found the answer.
For example, to drag from gridSource to gridTarget, you need one setting and three events:
1. Set the gridTarget attribute AllowDrop to True.
2. Implement the MouseDown event of gridSource. Save the content of the Cell to be dragged and save it to the clipboard.
3. Implement the DragDrop and DragEnter events of gridTarget. One difficulty in the DragDrop event is to decide which Cell to drag.
The Code is as follows:
MouseDown event of gridSource:
Code
Private void gridSource_MouseDown (object sender, MouseEventArgs e)
{
If (e. Button = MouseButtons. Left)
{
DataGridView. HitTestInfo info = this. gridSource. HitTest (e. X, e. Y );
If (info. RowIndex> = 0)
{
If (info. RowIndex> = 0 & info. ColumnIndex> = 0)
{
String text = (String) this. gridSource. Rows [info. RowIndex]. Cells [info. ColumnIndex]. Value;
If (text! = Null)
{
This. gridSource. DoDragDrop (text, DragDropEffects. Copy );
}
}
}
}
}
DragDrop event of gridTarget:
Code
Private void gridTarget_DragDrop (object sender, DragEventArgs e)
{
// Obtain the position to be dragged
Point p = this. gridTarget. PointToClient (new Point (e. X, e. Y ));
DataGridView. HitTestInfo hit = this. gridTarget. HitTest (p. X, p. Y );
If (hit. Type = maid. Cell)
{
DataGridViewCell clickedCell = this. gridTarget. Rows [hit. RowIndex]. Cells [hit. ColumnIndex];
ClickedCell. Value = (System. String) e. Data. GetData (typeof (System. String ));
// If you only want to drag to a specific column, such as Target Field Expression, you must first determine whether the column is a Target Field Expression, as shown below:
// If (0 = string. Compare (clickedCell. OwningColumn. Name, "Target Field Expression "))
//{
// ClickedCell. Value = (System. String) e. Data. GetData (typeof (System. String ));
//}
}
}
DragEnter event of gridTarget:
Code
Private void gridTarget_DragEnter (object sender, DragEventArgs e)
{
E. Effect = DragDropEffects. Copy;
}