How to target a row or datagridview cell from a DragDrop event?

void dataGridView1_DragDrop(object sender, DragEventArgs e)
    {
        object data = e.Data.GetData(typeof(string));

        MessageBox.Show(e.X + " " + e.Y + " " + dataGridView1.HitTest(e.X, e.Y).RowIndex.ToString());

        if (dataGridView1.HitTest(e.X, e.Y).Type == DataGridViewHitTestType.Cell)
        {
            MessageBox.Show("!");
        }

    }

If I try to drag an item into a datagridview using the above test code, I get the correct data from data.ToString()ok, but I can’t target a row or cell.

RowIndex.ToString() returns "-1", and the if statement returns false, so it never enters the encoded block.

What is wrong with my code?

+3
source share
1 answer

I believe that the coordinates passed from DragAndDrop are screen coordinates. I think you need to drop the points into the client coordinate space.

Point dscreen = new Point(e.X, e.Y);
Point dclient = dataGridView1.PointToClient(dscreen );
DataGridView.HitTestInfo hitTest = dataGridView1.HitTest(dclient.X,dclient.Y);

that hitTest.Rowwill have a row index

+12
source

Source: https://habr.com/ru/post/1724540/


All Articles