Responding to Clicks in the Windows Forms DataGrid Control in VB.NET

Responding to Clicks in the Windows Forms DataGrid Control.
  • 1753
After the Windows Forms DataGrid is connected to a database, you can monitor which cell the user clicked.

To detect when the user of the DataGrid selects a different cell

  • In the CurrentCellChanged event handler, write code to respond appropriately.

        Private Sub myDataGrid_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myDataGrid.CurrentCellChanged
            MessageBox.Show("Col is " & myDataGrid.CurrentCell.ColumnNumber _
               & ", Row is " & myDataGrid.CurrentCell.RowNumber _           & ", Value is " & myDataGrid.Item(myDataGrid.CurrentCell))
        End Sub

To determine which part of the DataGrid the user clicked

  • Call the HitTest method in an appropriate event handler, such as for the MouseDown or Click event.

    The HitTest method returns a DataGrid.HitTestInfo object that contains the row and column of a clicked area.

        Private Sub myDataGrid_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles myDataGrid.MouseDown
            Dim myGrid As DataGrid = CType(sender, DataGrid)
            Dim hti As System.Windows.Forms.DataGrid.HitTestInfo
            hti = myGrid.HitTest(e.X, e.Y)
            Dim message As String = "You clicked "

            Select Case hti.Type
                Case System.Windows.Forms.DataGrid.HitTestType.None
                    message &= "the background."
                Case System.Windows.Forms.DataGrid.HitTestType.Cell
                    message &= "cell at row " & hti.Row & ", col " & hti.Column
                Case System.Windows.Forms.DataGrid.HitTestType.ColumnHeader
                    message &= "the column header for column " & hti.Column
                Case System.Windows.Forms.DataGrid.HitTestType.RowHeader
                    message &= "the row header for row " & hti.Row
                Case System.Windows.Forms.DataGrid.HitTestType.ColumnResize
                    message &= "the column resizer for column " & hti.Column
                Case System.Windows.Forms.DataGrid.HitTestType.RowResize
                    message &= "the row resizer for row " & hti.Row
                Case System.Windows.Forms.DataGrid.HitTestType.Caption
                    message &= "the caption"
                Case System.Windows.Forms.DataGrid.HitTestType.ParentRows
                    message &= "the parent row"
            End Select

            Console.WriteLine(message)
        End Sub

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.