0

I'm having real trouble getting the validating event to fire. I have created a very simple windows form to demonstrate the problem. The form contains two textboxes and I'd expect the validating event to fire when the tab key is pressed in the first textbox, but it isn't. I'm using Powershell V4.0, running under Windows 7 Professional SP1. Code follows:-

Function ValidateField( [string]$FieldValue )
{
    Write-Host "ValidateField: Function Entered"

    if ( $FieldValue -eq $Null -Or $FieldValue.Trim().Length -eq 0 ) { Return $True } else { Return $False }
}

Function GenerateForm 
{
    Write-Host "GenerateForm: Function Entered"

    [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms"  ) | Out-Null
    [Reflection.Assembly]::LoadWithPartialName( "System.Drawing"  ) | Out-Null

    $Form = New-Object System.Windows.Forms.Form ; $IFWS = New-Object System.Windows.Forms.FormWindowState
    $Code = New-Object System.Windows.Forms.TextBox ; $Desc = New-Object System.Windows.Forms.TextBox
    $Form.ClientSize = New-Object System.Drawing.Size( 400,200 ) 
    $Form.StartPosition = "CenterScreen" ; $Form.add_Load( $FormLoad )

    $OnLoadForm_StateCorrection = { $Form.WindowState = $IFWS }

    $Code.DataBindings.DefaultDataSourceUpdateMode = 0 ; $Code.Location = New-Object System.Drawing.Size( 10,10 )
    $Code.Size = New-Object System.Drawing.Size( 40,20 ) ; $Code.CausesValidation = $True

    $Code_Validating = [System.ComponentModel.CancelEventHandler] { 

        { $Result = ( ValidateField $Code.Text )

        if ( $Result -eq $True ) { $_.Cancel = $True } }
    }

    $Form.Controls.Add( $Code )

    $Desc.DataBindings.DefaultDataSourceUpdateMode = 0 ; $Desc.Location = New-Object System.Drawing.Size( 100,10 )
    $Desc.Size = New-Object System.Drawing.Size( 169,20 ) ; $Form.Controls.Add( $Desc )

    $IFWS = $Form.WindowState ; $Form.add_Load( $OnLoadForm_StateCorrection ) ; $Form.ShowDialog() | Out-Null
}

GenerateForm

It may well be that I'm just missing something very very simple - but this has been driving me mad for 3 days now, so any help gratefully accepted.

Crono
  • 10,211
  • 6
  • 43
  • 75

1 Answers1

0

I don't see where you are connecting to the Validating event. Replace your $Code_Validating assignment with this:

$Code.add_Validating({ 
    $result = ValidateField $sender.Text
    if ($result) {$eventArgs.Cancel = $true}
})
Keith Hill
  • 194,368
  • 42
  • 353
  • 369