Windows forms – add data to list view on button click [duplicate]

Because an event-handling script block added with e.g. .Add_Click() runs in in a child scope of the caller, assigning to variable $Results there ($Results = ...) creates a scope-local variable that neither the scope in which the event handler was set up nor subsequently invoked event handlers can see.

To create a variable in the script scope, which subsequently invoked event handlers can see as well[1], use the $script: scope specifier:

$button_UpdateTS.Add_Click( { $script:Results = ... } )

Note:

  • If the scope in which the event handlers are set up isn’t the script scope (e.g., if the code is inside a function) and you want to more generically reference that scope from within an event handler, use Set-Variable -Scope 1 -Name Results -Value ..., which targets the respective parent scope.[1]

  • An alternative to setting a variable in the parent scope explicitly is to use a hashtable defined in the parent scope whose entries can be used in lieu of variables that the event-handler script blocks can modify too.[2] See this answer for an example.


[1] For more information about scopes in PowerShell, see the bottom section of this answer.

[2] This technique works, because even though the variable containing the hashtable is defined in the parent scope, the child scope can access its value and modify the entries of the referenced hashtable object rather than the variable itself.

Leave a Comment