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 determine the row or column of a DataGrid 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.

X & Y are in the grid' coordinates. If they are in screen coordinates, call dataGrid1.PointToClient method

[C#]

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() );
}

[Visual Basic]

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

Contributed from George Shepherd's Windows Forms FAQ



Page view counter