locked
DataGridView Events RRS feed

  • Question

  • I created the following event handlers. When clicking on a cell, OnClick_Cell is called. When clicking on a column header, OnClick_CollumnHeader is called but at the same time, OnClick_Cell is also fired. Is it something special? Thanks

    Function OnClick_Cell() { Write-Host 'Cell Clicked' }
    Function OnClick_CollumnHeader() { Write-Host 'Header Clicked' }
    $Form = New-Object System.Windows.Forms.Form
    $Form.Size = New-Object System.Drawing.Size(600,400)
    $DataGridView = New-Object System.Windows.Forms.DataGridView
    $DataGridView.Location =  New-Object System.Drawing.Point(5,25)
    $DataGridView.Size = New-Object System.Drawing.Size(565,410)
    $DataGridView.Add_CellClick({OnClick_Symbol})
    $DataGridView.Add_ColumnHeaderMouseClick({OnClick_CollumnHeader})
    $col1 = New-Object System.Windows.Forms.DataGridViewTextboxColumn
    $col1.Name = 'Col1'
    $col1.Width = 50
    $DataGridView.Columns.Add($col1)
    $col2 = New-Object System.Windows.Forms.DataGridViewTextboxColumn
    $col2.Name = 'Col2'
    $col2.Width = 50
    $DataGridView.Columns.Add($col2)
    $Form.Controls.Add($DataGridView)
    $Form.ShowDialog()


    • Edited by Ian3 Sunday, November 10, 2019 3:56 AM
    Sunday, November 10, 2019 3:23 AM

All replies

  • A header cell is still a cell. All event handlers registered to a cell will file.

    To solve this you have to have a reason for using the event.  Once you have a need then you can pick the event.  To choose events you need to understand the whole forms event model then you will understand which event you need.

    When defining event code do not use functions.  It is unnecessary and can cause scoping issues that are hard to debug.

    This is how to define event code:

    $statusDataGridView_CellClick = {
        Write-Host 'Cell Clicked'
    }
    $statusDataGridView_ColumnHeaderMouseClick = {
        Write-Host 'Header Clicked'
    }
    
    # ...
    $statusDataGridView = New-Object System.Windows.Forms.DataGridView
    $statusDataGridView.Name = 'statusDataGridView'
    # ...
    $statusDataGridView.add_CellClick($statusDataGridView_CellClick)
    $statusDataGridView.add_ColumnHeaderMouseClick($statusDataGridView_ColumnHeaderMouseClick)
    


    \_(ツ)_/

    Sunday, November 10, 2019 7:17 AM