Click here to Skip to main content
Click here to Skip to main content

Creating a Row Highlighter for a DataGridView Control

, 6 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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

License

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

Share

About the Author

Simon_Whale
Software Developer Oak Underwriting
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 6 Mar 2014
Article Copyright 2014 by Simon_Whale
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid