HOME PAGE | DOWNLOAD | TUTORIALS | XtraReports
Devexpress

Thursday, July 19, 2012

Identifying the Grid's Element Located Under the Mouse Cursor

The XtraGrid consists of many different visual elements. Column headers, summary footers, cells and row indicators to name a few. Sometimes, it is necessary to identify this visual elements based on the position of the mouse.
1.       For example, I have a sample project here with an XtraGrid on a form.
2.       I can use the grid view’s CalcHitInfo method to determine the grid’s visual element based on the passed-in coordinates.
3.       The CalcHitInfo will return a GridHitInfo structure containing all the hit information that I need.
4.       In particular, the GridHitInfo.HitTest enum will help me identify the exact element that the mouse is on.
5.       We can learn more about this enum by exploring it in the MouseMove event.


private void gridControl1_MouseMove(object sender, MouseEventArgs e) {
GridHitInfo hi = gridView1.CalcHitInfo(e.X, e.Y);
this.Text = hi.HitTest.ToString();
}

6.  Here, we simply display the value of the HitTest in the title.

7.  A common scenario for CalcHitInfo is determaning a data row from a double click event.

private void gridControl1_DoubleClick(object sender, EventArgs e) {
       GridHitInfo hi = gridView1.CalcHitInfo(
(sender as Control).PointToClient(Control.MousePosition));
       if (hi.RowHandle >= 0) {
XtraGrid_Demo.ContactsDataSet.CustomersRow dr =              
gridView1.GetDataRow(hi.RowHandle) as
XtraGrid_Demo.ContactsDataSet.CustomersRow;
              if (dr != null) {
                     MessageBox.Show(dr.FirstName);
              }
       }
    }

8.  We will request the GridHitInfo based on the current mouse position and use the grid view’s GetDataRow method to get the actual data row object, based on the hit info that we have.

9.  Now, I can run the application and double click on any row. I should see a MessageBox displaying a FirstName of my customer.


Enhanced by Zemanta

No comments:

Post a Comment