简体   繁体   中英

How to acquire the Index of a Row that is being dragged from a dataGridView to a different control?

I am trying to get the index of a row. The row is to be dragged from the dataGridView onto a treeView. I was trying to get the index on the MouseDown event of the dataGridView, before anything has started to be dragged.

    private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            var rowNum = dataGridView1.SelectedCells[0].RowIndex;
            dragItemID = dataGridView1["ID", rowNum].Value.ToString();
            dataGridView1.DoDragDrop(dragItemID, DragDropEffects.Copy);
        }
    }

Let me know if there is a better way to do it, because as it stands this doesn't return the correct index, and instead returns the index of the top row (the first row in the dataGridView)

You should use different event, try with CellMouseDown . Inside EventArgs of that event you have information about RowIndex .

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        dragItemID = dataGridView1["ID", e.RowIndex].Value.ToString();
        dataGridView1.DoDragDrop(dragItemID, DragDropEffects.Copy);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM