1

How can you create clone objects using a loop so that you can access each of them individually? For example 10 buttons:

for ($i = 1; $i -le 10; $i++) {

   $Obj = New-Object System.Windows.Forms.Button

   $Obj.Left = 30 * $i + 10
   $Obj.Top = 10
   $Obj.Width = 30
   $Obj.Height = 30

   $Form.Controls.Add($Disk)
}

And then make assignments in the script, let's say the text:

$Obj1.Text = 'One'
$Obj2.Text = 'Two'
...
$Obj10.Text = 'Ten'

Somehow, in the loop, it is necessary to specify the names of the objects $Obj1, $Obj2...$Obj10. Perhaps using this:

$Obj = New-Variable -Name ('Obj' + [string]$i)

But my knowledge is not so good to do it right away. Thanks for answers.

1
  • 1
    why not use the array? something like $Obj[$Index].Text? Commented Dec 29, 2019 at 13:50

1 Answer 1

2

Something like this?

$form = New-Object System.Windows.Forms.Form

#Add flow layout panel
$FlowLayoutPanel = New-Object System.Windows.Forms.FlowLayoutPanel
$FlowLayoutPanel.FlowDirection=[System.Windows.Forms.FlowDirection]::LeftToRight
$FlowLayoutPanel.Dock=[System.Windows.Forms.DockStyle]::Left
$FlowLayoutPanel.Width=200
$FlowLayoutPanel.BorderStyle=[System.Windows.Forms.BorderStyle]::FixedSingle
$form.Controls.Add($FlowLayoutPanel)

#define click event for button
$Button_Click = 
{param($sender,$eventarg)

[System.Windows.Forms.Button] $currentbutton=$sender

    [System.Windows.Forms.MessageBox]::Show("You have click on : " +  $currentbutton.Text, "My Dialog Box")
}



#Add Button into flow layout panel and associate event for every button
for ($i = 1; $i -le 10; $i++) {

   $Obj = New-Object System.Windows.Forms.Button
   $Obj.Width = 80
   $Obj.Height = 30
   $Obj.Text="Button$i" 
   $Obj.Add_Click($Button_Click)

   $FlowLayoutPanel.Controls.Add($Obj)
}



$result = $form.ShowDialog() | Out-Null 
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.