释放鼠标左键后如何设置行选择?

时间:2013-08-13 13:58:44

标签: winforms c#-4.0

我有datagridview。在这个gridview中,当我左键单击并按住该行并将其拖放到另一行时,它工作正常,但行的选择保持不变。

例如。如果我选择第2行并将其拖到第4行,第2行会在位置4处下降,但行选择保持不变。我希望当我把它放到第4行时,选择的行应该是第4行。

我已经完成了一些拖放功能的代码。

private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
    if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        // 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_MouseDown(object sender, MouseEventArgs e)
{
    rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (rowIndexFromMouseDown != -1)
    {           
        Size dragSize = SystemInformation.DragSize;
        dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
                                                       e.Y - (dragSize.Height / 2)),
                            dragSize);
    }
    else
        // Reset the rectangle if the mouse is not over an item in the ListBox.
        dragBoxFromMouseDown = Rectangle.Empty;
}

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

private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
    Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));

    // Get the row index of the item the mouse is below. 
    rowIndexOfItemUnderMouseToDrop =
        dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

    // If the drag operation was a move then remove and insert the row.
    if (e.Effect== DragDropEffects.Move)
    {
        DataGridViewRow rowToMove = e.Data.GetData(
            typeof(DataGridViewRow)) as DataGridViewRow;
        dataGridView1.Rows.RemoveAt(rowIndexFromMouseDown);
        dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);

    }
}

1 个答案:

答案 0 :(得分:0)

添加行

        dataGridView1.Rows[rowIndexOfItemUnderMouseToDrop].Selected = true;
        dataGridView1.Rows[rowIndexFromMouseDown].Selected = false;

dataGridView1_DragDrop的末尾,以便选择更改。您已经有问题地更改了行,这意味着dataGridView的选择没有随之改变。