如何在任何单元格的鼠标hover上突出显示datagridview的行和/或列标签(在c#中)?

使用Windows窗体上的DataGridView控件,当您将鼠标移动到行标签(或列标签)上时,它(标签单元格)背景将变为蓝色阴影(或其他颜色,具体取决于您的Windows配色方案)。

我希望在将鼠标移动到网格中的任何单元格时生成该效果 – 即突出显示鼠标当前hover在其上的行的行标签。

使用mouseover事件更改当前行样式的逻辑非常简单。 我可以更改该行的其他属性(比如说背景颜色),但我真的想要比这更微妙的东西,我认为突出显示行标签会非常有效。

可以这样做 – 如果是这样的话? (最好是C#)

您可以覆盖OnCellPainting事件以执行您想要的操作。 根据DataGridView的大小,您可能会看到闪烁,但这应该是您想要的。

class MyDataGridView : DataGridView { private int mMousedOverColumnIndex = int.MinValue; private int mMousedOverRowIndex = int.MinValue; protected override void OnCellMouseEnter(DataGridViewCellEventArgs e) { mMousedOverColumnIndex = e.ColumnIndex; mMousedOverRowIndex = e.RowIndex; base.OnCellMouseEnter(e); base.Refresh(); } protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e) { if (((e.ColumnIndex == mMousedOverColumnIndex) && (e.RowIndex == -1)) || ((e.ColumnIndex == -1) && (e.RowIndex == mMousedOverRowIndex))) { PaintColumnHeader(e, System.Drawing.Color.Red); } base.OnCellPainting(e); } private void PaintColumnHeader(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, System.Drawing.Color color) { LinearGradientBrush backBrush = new LinearGradientBrush(new System.Drawing.Point(0, 0), new System.Drawing.Point(100, 100), color, color); e.Graphics.FillRectangle(backBrush, e.CellBounds); DataGridViewPaintParts parts = (DataGridViewPaintParts.All & ~DataGridViewPaintParts.Background); e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None; e.AdvancedBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.None; e.Paint(e.ClipBounds, parts); e.Handled = true; } } 

您可以挂钩DataGridView的CellMouseEnter和CellMouseLeave事件,然后相应地更改背景颜色。 像这样的东西:

  private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) //column header / row headers { return; } this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightBlue; } private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) //column header / row headers { return; } this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White; } 

我知道你已经对此有了回应,但我会分享不同的东西。

这样, 整行都被绘了 。 我刚刚修改了@BFree评论。

  private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) //column header / row headers { return; } foreach (DataGridViewCell cell in this.dataGridView1.Rows[e.RowIndex].Cells) { cell.Style.BackColor = Color.LightBlue; } } private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) //column header / row headers { return; } foreach (DataGridViewCell cell in this.dataGridView1.Rows[e.RowIndex].Cells) { cell.Style.BackColor = Color.White; } }