Joshua Williams
Joshua Williams

Reputation: 58

Powershell: Event in Foreach loop

I'm having problems with a foreach loop and setting a Add_MouseClick event.

Each loop the function generates a new clickable label. While the .Text variable setting works as intended, when setting the event listener, it will write out the last generated $labelName, regardless of which is clicked.

foreach($account in $resUserNameSearchArray){
    #Set form object variables
    $script:labelName = "res" + $i 

    #Form Variable
    Set-Variable -Name $labelName -Value (New-Object System.Windows.Forms.Label)
    (Get-Variable $labelName -ValueOnly).Text = "$account"
    (Get-Variable $labelName -ValueOnly).Add_MouseClick{  
        Write-Host "$labelName"
    }...

There's a few non-relevant lines removed (location, font,etc)

Upvotes: 0

Views: 408

Answers (1)

Joshua Williams
Joshua Williams

Reputation: 58

I needed to use Write-Host $this.text within the Add_Click event to pull in the .text of the foreach variable.

Upvotes: 2

Related Questions