Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've got a problem with ForEach loop. Im trying to loop through multiple variables of same kind just increment different. Im trying to change the TextBox Text depending on if Label from same row has text.

This is how I could make it to just write and IF sentence for each Label but I was looking a way to loop each of these blocks through ForEach loop. I've got total of 8 Labels and Textboxes.

Here is the code: ( Im sure you'll figure out what I'm after :) )

IF ( $Label1.Text.Length -ne 0 ) 
{ 
    $Label1.Visible = $true
    $TextBox1.Visible = $true

    $TextBox1.Text = ( "Enter new name for " + $Label1.Text ) 
}

example of ForEach

$Count = 1..8

$Count | ForEach-Object {

     IF ( $Label($_).Text.Length -ne 0 )
     {
          $Label($_).Visible = $true
          $TextBox($_).Visible = $true

          $TextBox($_).Text = ( "Enter new name for " + $Label($_).Text )
     }
}

etc...

I tried putting variables in array and loop through that way but ofcourse array changes the type to string and it doesnt work...

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Give this a try, I can't test it using label & textbox object but it can work tuning it better:

 1..8  | ForEach-Object {

     IF ( (iex "`$Label$_.Text.Length") -ne 0 )
     {
        iex  "`$Label$_.Visible = `$true"
        iex  "`$TextBox$_.Visible = `$true"

        iex  "`$TextBox$_.Text = 'Enter new name for ' + `$Label$_.Text"
     }
}
share|improve this answer
    
This worked for me. I have no idea what this is doing but trying to figure it out! –  OlliE Aug 6 '13 at 12:31
    
@user2656503 iex is the alias for invoke-expression ( try get-help invoke-expression -full to read about it ). Remember to accept this as the answer, thanks. –  CB. Aug 6 '13 at 12:40

You can use the Get-Variable cmdlet for that purpose:

 1..8 | ForEach-Object {

     if ( (Get-Variable "Label$_").Value.Text.Length -ne 0 )
     {
         (Get-Variable "Label$_").Value.Visible = $true
         (Get-Variable "Label$_").Value.Visible = $true
         (Get-Variable "Label$_").Value.Text = ( "Enter new name for " + (Get-Variable "Label$_").Value.Text )
     }
}
share|improve this answer
    
Are you missing the .value. inside the if block right? –  CB. Aug 6 '13 at 12:22
    
Didnt work for me, I this this cant access the .net objects. –  OlliE Aug 6 '13 at 12:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.