如何识别在 DataGridView 中悬停的特定单元格

How to identify the specific cell hovered over in DataGridView

我在所有 datagridview 行的末尾放了一张图片,以便在按下时删除行。 我想在特定单元格鼠标悬停时更改该图片的颜色(为了向用户表明它是一个交互式按钮)。

然而,在所有解决方案中,我发现完整的 DGV 鼠标悬停被解释。 我需要的是:了解如何在单元格鼠标悬停期间找到悬停在上的特定单元格。

如果这是 WindowsForms:

//when mouse is over cell
    private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
        {
            dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Black;
        }
    }
//when mouse is leaving cell
    private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
        {
            dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;
        }
    }

老问题,@titol 的回答很好,但我不喜欢为此使用事件 CellMouseMove(触发太频繁)。

我建议用CellMouseEnter,当然还有CellMouseLeave,在鼠标进入时捕捉。像这样:

    void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e) {
        if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
        var gv = sender as DataGridView;
        var column = gv.Columns[e.ColumnIndex];
        if (myLogicToCheckIfIsTrashButtonColumn(column)) {
            gv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Black;
            gv.InvalidateCell(gv.Rows[e.RowIndex].Cells[e.ColumnIndex]);
        }
    }

    void downloadFilesGv_CellMouseLeave(object sender, DataGridViewCellEventArgs e) {
        if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
        var gv = sender as DataGridView;
        var column = gv.Columns[e.ColumnIndex];
        if (myLogicToCheckIfIsTrashButtonColumn(column)) {
            gv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;
            gv.InvalidateCell(gv.Rows[e.RowIndex].Cells[e.ColumnIndex]);
        }
    }