C# - Coordinates to Col/Row index

When using a DataGrid or a DataGridView control, have you ever had mouse events such as MouseDown or MouseClick, where you wanted to know in which cell (or part of the table) is the pointer pointing to? You have the X and Y coordinates passed in the MouseEventArgs parameter, but how would you translate them to column and row indices?

One way is to apply a long formula involving those coordinates, the size of the table, sizes of cells, headers, etc... But obviously, that's tedious for a C# developer. That's the primitive way (or the C way) of handling it.

Thanks to a workmate, I discovered the magic of the HitTestInfo class. An instance of this class will give you the row and column indexes amongst other information. To create the object, say in a MouseDown event, you do the following:

private void dataGridView1_MouseDown( object sender, MouseEventArgs e )
{
System.Windows.Forms.DataGridView.HitTestInfo h = dataGridView1.HitTest( e.X, e.Y );
}

A DataGridView object contains the method HitTest(), which, given the x and y coordinates, returns an object of type HitTestInfo with all the information you need. Note the namespace of the class: System.Windows.Forms.DataGridView. If you are using a DataGrid, the class would be System.Windows.Forms.DataGrid.HitTestInfo (2 different classes).

With our object created, we can get various useful information (much more useful than x and y).

HitTestInfo.Type gets what part of the table is at the coordinates (Ex. column header, cell, etc...)
HitTestInfo.ColumnIndex & HitTestInfo.RowIndex are self explanatory.

if ( h.Type == System.Windows.Forms.DataGridViewHitTestType.ColumnHeader )
MessageBox.Show( "You clicked on a column header." );
else
MessageBox.Show( h.Type.ToString() + '(' + h.ColumnIndex + ',' + h.RowIndex + ')' );

Note that if you are using a DataGrid, the HitTestInfo.Type returns an element from the enumeration System.Windows.Forms.DataGrid.HitTestType.

Tags: , | |

3 comments:

  1. Anonymous Says:

    Good brief and this post helped me alot in my college assignement. Thanks you on your information.

  2. Anonymous Says: This comment has been removed by a blog administrator.
  3. Anonymous Says:

    Great Site. Was added to mybookmarks. Greetings From USA.