0

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)

4
  • Here is the rest of the function's code pastebin.com/Bx4g2nx7 Commented Mar 30, 2017 at 14:43
  • Yes, I've been working through it piece by piece. Calling Write-Host $labelName outside of the Add_MouseClick event works as intended, it appears to only occur when it's wrapped in that event. Commented Mar 30, 2017 at 15:02
  • Your click action is going to be evaluated at when you click it. So $labelname will 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. Commented Mar 30, 2017 at 16:42
  • That got me where I needed! Write-Host $this.text did it! Thank you. Commented Mar 30, 2017 at 18:20

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.