Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I translate a point to a cell in a DataGrid?

If the point is in screen coordinates, then convert it to client coordinates of the DataGrid and use HitTest to find the row and column.

using System.Drawing;
using System.Windows.Forms;

private DataGridCell CellFromPoint( DataGrid dataGrid, Point pointInScreenCoords )
{
  Point pointInClientCoords = dataGrid.PointToClient( pointInScreenCoords );
  DataGrid.HitTestInfo hti = dataGrid.HitTest( pointInClientCoords );
  return new DataGridCell( hti.Row, hti.Column );
}

If you are using context menus for catching right-clicks in the DataGrid, you have to do a little work to remember where the original right-click point was, since the point passed in through the menu event arguments may not reflect this original click. One solution is to remember the click in the DataGrid MouseDown event, and then use the code above to retrieve the grid cell from within the menu handler.

using System.Drawing;
using System.Windows.Forms;

private Point rightMouseDownPoint;

private void dataGrid1_MouseDown( object sender, MouseEventArgs e )
{
  if ( e.Button == MouseButtons.Right )
    rightMouseDownPoint = Cursor.Position;
}

private void menuItem1_Click( object sender, System.EventArgs e )
{
  DataGridCell cell = CellFromPoint( dataGrid1, rightMouseDownPoint );
  // ...
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter