Live Chat Icon For mobile
Live Chat Icon

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

Platform: WinForms| Category: Datagrid

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

Share with

Related FAQs

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

Please submit your question and answer.