Live Chat Icon For mobile
Live Chat Icon

How can I translate a point to a cell in the datagrid

Platform: WinForms| Category: Datagrid

If the point, say pt, is in screen coordinates, you can use code such as


Point p1 = dataGrid1.PointToClient(pt);
MessageBox.Show(dataGrid1.HitTest(p1).ToString());

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


Point rightMouseDownPoint;

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

private void menuItem4_Click(object sender, System.EventArgs e)
{
    Point pt = dataGrid1.PointToClient(rightMouseDownPoint);
    MessageBox.Show(dataGrid1.HitTest(pt).ToString());
}

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.