Click here to Skip to main content
15,882,209 members
Articles / Programming Languages / C#
Tip/Trick

Creating a Row Highlighter for a DataGridView Control

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
6 Mar 2014CPOL 14.5K   8  
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.

C#
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:

C#
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Yellow;

History

  • Original version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --