Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

5. Windows Forms Datagrid

5.31 How do I get the row or column that has been clicked on?


You can use the DataGrid's HitTest method, passing it a point in the grid's client coordinate system, and returning a HitTestInfo object that holds all the row and column information that you want.

[C#]
// X & Y are in the grid' coordinates. If they are in screen coordinates, call dataGrid1.PointToClient method
System.Drawing.Point pt = new Point(X, Y);
DataGrid.HitTestInfo hti = dataGrid1.HitTest(pt);
if(hti.Type == DataGrid.HitTestType.Cell)
{
     MessageBox.Show(dataGrid1[hti.Row, hti.Column].ToString());
}
else if(hti.Type == DataGrid.HitTestType.ColumnHeader)
{
     MessageBox.Show(((DataView) DataGrid1.DataSource).Table.Columns[hti.Column].ToString());
}

[VB.NET]
' X & Y are in the grid' coordinates. If they are in screen coordinates, call dataGrid1.PointToClient method
Dim pt = New Point(X, Y)
Dim hti As DataGrid.HitTestInfo = dataGrid1.HitTest(pt)
If hti.Type = DataGrid.HitTestType.Cell Then
     MessageBox.Show(dataGrid1(hti.Row, hti.Column).ToString())
Else
     If hti.Type = DataGrid.HitTestType.ColumnHeader Then 'assumes datasource is a dataview
          MessageBox.Show(CType(DataGrid1.DataSource, DataView).Table.Columns(hti.Column).ToString())
     End If
End If