Google
WWW Yariv Hammer's Code Site

Monday, October 24, 2005

How-To Select a Row in the DataGrid When the Mouse is Over it

Introduction
If you want to select a row in the DataGrid when the user point the mouse on it (without clicking!!!), Then you will need to do some coding.
The DataGrid has a HitTest method to help us get the cell that the mouse is pointing at. We can use the Select and Unselect methods.

Code
----------------------------------------------
Create a MouseMove event handler to the DataGrid and place this code:

private int _prevRow = -1;
private void dataGrid1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
   DataGrid.HitTestInfo info = dataGrid1.HitTest(e.X, e.Y);
   if (info.Type == DataGrid.HitTestType.Cell)
   {
      if (_prevRow != info.Row)
      {
         this.BindingContext[dataGrid1].EndCurrentEdit();
         if (_prevRow != -1)
         dataGrid1.UnSelect(_prevRow);          dataGrid1.Select(info.Row);
         _prevRow = info.Row;
      }
   }
   else
   {
      if (_prevRow != -1)
      {
         dataGrid1.UnSelect(_prevRow);
         _prevRow = -1;
      }
   }
}

-------------------------------------------------

Feel free to use everything here. Add links to my site if you wish.

Do not copy anything to other sites without adding link to here.

All the contents of the site belong to Yariv Hammer.