0

Im really embarrassed asking this, but I have a script which I'm trying to make it look better, and less repetetive.

It has the following lines:

$textbox41.Add_Click({if ($Box41Trigger){$textbox41.text = ""; $textbox41.ForeColor="black";$script:Box41trigger=$false}})
$textbox42.Add_Click({if ($Box42Trigger){$textbox42.text = ""; $textbox42.ForeColor="black";$script:Box42trigger=$false}})
$textbox43.Add_Click({if ($Box43Trigger){$textbox43.text = ""; $textbox43.ForeColor="black";$script:Box43trigger=$false}})

You can see those 3 lines are repetitive only changing 41, 42, 43 etc. in two locations.

How can I make it look better? it looks so bad.

2 Answers 2

2

you can do this with a loop:

In order to test it, I created 3 folders in C:\ (1Test1-Kopie,2Test2-Kopie,3Test3-Kopie)

for ($Z=1; $Z -le 3; $Z++) 

{Get-item -Path "C:\${Z}Test${Z} - Kopie"} 

For your code i replaced 41,42 and 43 with ...4${Z}...as only the last digit is changing...try around to figure out if it works

for ($Z=1; $Z -le 3; $Z++) 

{$textbox4${Z}.Add_Click({if ($Box4${Z}Trigger){$textbox4${Z}.text = ""; $textbox4${Z}.ForeColor="black";$script:Box4${Z}trigger=$false}})}
Sign up to request clarification or add additional context in comments.

Comments

1
$textBoxList = @(
    $textBox41,
    $textBox42,
    $textBox43
)

foreach ($textBox in $texBoxList) {
    $textBoxTrigger = 'box' + $textBox.Name.Substring($textbox.length -2) + 'Trigger'
    $textBox.Add_Click( {
        if ($textBoxTrigger) { 
            $textBox.text = ""; 
            $textBox.ForeColor="black"; 
            $script:textBoxTrigger=$false
        }
    })
}

Another option for grabbing the number on that second variable. Not certain on the name of the "Name" property on a textbox in powershell, so that may need to change to whatever the objects actual name property is when pulling the substring.

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.