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)
Write-Host $labelNameoutside of theAdd_MouseClickevent works as intended, it appears to only occur when it's wrapped in that event.$labelnamewill be what it is at that moment (the last created), not what it was when the click action was made. So you need to get what label was clicked from inside the mouse click, which I can't think of how to do off the top of my head.Write-Host $this.textdid it! Thank you.