Recently, while working on a grid in Winforms, I found myself trying to see if I could highlight the row as I moused over it purely as a cosmetic enhancement to the application.
Using the Code
I used the
MouseMove event of the
DataGridView as this event is fired when the mouse is over the control and is more suited to altering the controls appearance. Further reading on the event is on MSDN.
int previousRow = 0;
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
DataGridView.HitTestInfo testInfo = DataGridView1.HitTest(e.X, e.Y);
if(testInfo.RowIndex >= 0 && testInfo.RowIndex != PreviousRow)
dataGridView1.Rows[previousRow].Selected = false;
dataGridView1.Rows[testInfo.RowIndex].Selected = true;
previousRow = testInfo.RowIndex;
Points of Interest
If you wish to change the background colour of the selected row, you will need to change
SelectionBackColor which can be found by using the following:
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Yellow;