Creating a Row Highlighter for a DataGridView Control





5.00/5 (2 votes)
Highlighting a row with a mouseover event of the DataGridView in Winforms.
Introduction
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);
//Need to check to make sure that the row index is 0 or greater as the first
//row is a zero and where there is no rows the row index is a -1
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;
History
- Original version