在C#中,有没有办法将DataGridView单元格的内容拖到另一个单元格?

时间:2012-07-16 15:18:47

标签: c# datagridview drag-and-drop

我有DataGridView dgv。在dgv的一个单元格中,我有一个带灰色阴影的单元格(其余单元格为空白和白色)。我希望能够将该阴影单元格拖动到该列中的另一个单元格,并从前一个单元格的位置,值,行#,列#等以及新单元格的位置,值,行/列中获取信息。这可能吗?这非常类似于国际象棋棋盘,其中“棋子”通过拖动从一个单元格移动到另一个单元格。

1 个答案:

答案 0 :(得分:5)

下面的代码有效,但几乎可以肯定地整理一下。它基于DataGridViewFAQ的示例。在那个例子中,他们拖动行,所以我改变了一些东西来移动单元格值并使用鼠标右键。

我没有工作的一件事(虽然我没有花很长时间),却是使用DoDragDrop参数传递被拖动的单元格。该对象通过null传递,所以我只是将它放在一个表单级变量中。

private DataGridViewCell drag_cell;

private Rectangle dragBoxFromMouseDown;

public Form1()
{
    InitializeComponent();
    dataGridView1.AllowDrop = true;
    dataGridView1.MouseDown += new MouseEventHandler(dataGridView1_MouseDown);
    dataGridView1.MouseMove += new MouseEventHandler(dataGridView1_MouseMove);
    dataGridView1.DragOver += new DragEventHandler(dataGridView1_DragOver);
    dataGridView1.DragDrop += new DragEventHandler(dataGridView1_DragDrop);
}

private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
    if ((e.Button & MouseButtons.Right) == MouseButtons.Right)
    {
        // If the mouse moves outside the rectangle, start the drag.
        if (dragBoxFromMouseDown != Rectangle.Empty &&
            !dragBoxFromMouseDown.Contains(e.X, e.Y))
        {

            // Proceed with the drag and drop, passing in the list item.                    
            DragDropEffects dropEffect = dataGridView1.DoDragDrop(
            dataGridView1.Rows[rowIndexFromMouseDown],
            DragDropEffects.Move);
        }
    }
}

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

private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
    // The mouse locations are relative to the screen, so they must be 
    // converted to client coordinates.
    Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));

    // Get the row index of the item the mouse is below. 
    DataGridView.HitTestInfo hti = dataGridView1.HitTest(clientPoint.X, clientPoint.Y);
    DataGridViewCell targetCell = dataGridView1[hti.ColumnIndex, hti.RowIndex];


    // If the drag operation was a move then remove and insert the row.
    if (e.Effect == DragDropEffects.Move)
    {
        targetCell.Value = drag_cell.Value;
        dataGridView1.Refresh();
    }
}


void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        DataGridView.HitTestInfo hti = dataGridView1.HitTest(e.X, e.Y);
        drag_cell = dataGridView1[hti.ColumnIndex, hti.RowIndex];
        // Proceed with the drag and drop, passing in the list item.                    
        DragDropEffects dropEffect = dataGridView1.DoDragDrop(
        drag_cell,
        DragDropEffects.Move);
    }
}