With a DataGridView control on a Windows form, when you move the mouse over a row label (or column label) it\'s (the label cell) background changes to a shade of blue (or ot
You could override the OnCellPainting event to do what you want. Depending on the size of your DataGridView, you might see flickering, but this should do what you want.
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;
}
}
You can hook into the DataGridView's CellMouseEnter and CellMouseLeave events and then change the backcolor accordingly. Something like this:
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;
}
I know you already have the response for this, but I will share something different.
This way, the whole row is painted. I just modified @BFree comments a little bit.
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;
}
}