Brick
Brick

Reputation: 119

Auto Generating field variables

I use the following code to generate checkboxes on a powershell GUI-

$databases_checkBox_1 = New-Object system.windows.Forms.CheckBox
$databases_checkbox_1.Width = 200
$databases_checkBox_1.location = new-object system.drawing.point(245,$y)
$y=$y+30

$databases_checkBox_2 = New-Object system.windows.Forms.CheckBox
$databases_checkbox_2.Width = 200
$databases_checkBox_2.location = new-object system.drawing.point(245,$y)
$y=$y+30

$databases_checkBox_3 = New-Object system.windows.Forms.CheckBox
$databases_checkbox_3.Width = 200
$databases_checkBox_3.location = new-object system.drawing.point(245,$y)
$y=$y+30

$databases_checkBox_4 = New-Object system.windows.Forms.CheckBox
$databases_checkbox_4.Width = 200
$databases_checkBox_4.location = new-object system.drawing.point(245,$y)
$y=$y+30

But I want to generate 'X' amount of checkboxes, as the list could be up to a hundred - any idea how to get them to auto generate?

Upvotes: 0

Views: 166

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Run the checkbox creation code in a loop as many times as the number of checkboxes you want to create (don't forget to add the controls to the form after creating them). At the end of each iteration output the created object and collect all output of the loop in a variable:

$checkboxes = 0..3 | ForEach-Object {
    $cb = New-Object Windows.Forms.CheckBox
    $cb.Width = 200
    $cb.Location = New-Object Drawing.Point(245, $y)
    $y += 30

    $form.Controls.Add($cb)

    $cb
}

Once you have that you can access each checkbox by its index in the array. For instance:

$checkboxes[2].Checked

will give you the "checked" status of the third checkbox (PowerShell arrays are zero-based).

Upvotes: 1

notjustme
notjustme

Reputation: 2494

Not the prettiest solution but it should work. Only creating 5 variables (0..4) in this example.

$y = 0
0..4 | foreach {
    $currentVar = New-Variable -Name databases_checkBox_$_ -Value $(New-Object System.Windows.Forms.CheckBox) -PassThru
    $currentVar.Value.Width = 200
    $currentVar.Value.Location = New-Object System.Drawing.Point(245,$y)
    $y = $y+30
}

You can doublecheck by running Get-Variable databases_checkBox*.

That being said - if you're after hundreds of them it'll get messy real quick. Take Ansgar's comment as a word of advice.

Upvotes: 0

Related Questions