2

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

4

1 回答 1

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);
    }
}
于 2012-07-16T18:40:04.640 回答