DataGridView单元格鼠标悬停背景色更改

4

当鼠标悬停在特定单元格上时,我希望更改DataGridView中单元格的背景颜色。

尝试的代码:

private void dataGridView_whateventwillcomehere(object sender, DataGridViewCellEventArgs e)
        {

        }
1个回答

13

尝试在 CellMouseMove 事件上使用此代码

private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Blue;
}

你需要使用CellMouseLeave事件来恢复颜色。

private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
}

你需要提及“列名”而不是“e.ColumnIndex”来指定特定的单元格。 - NASSER
2
在DGV构造函数中,您还需要设置双缓冲绘制,否则更改单元格样式会在鼠标移动到DGV上时引起闪烁。this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); - Patrick from NDepend team

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接