Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Array contents go missing?

$
0
0

I am using PowerShell to display a form, but when it comes to retrieving the content, it seems to have disappeared.

Here is the sample code. 

The array variable gets created in the body of the script.

The array gets populated in in the form.load event.

But the button_click event sees the array as being empty.

I have been trying a number of things to get this to work, but I have run out of ideas.

Any suggestions would be much appreciated

 

cls
Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form

$Form.Width = 450
$Form.Height = 250
$Form.AutoScroll = $True
$Form.Text = "Array scoping Demo"
[System.Windows.Forms.Application]::EnableVisualStyles()

$txtDemo1 =  [System.Collections.ArrayList]@()
$txtDemo1.Count
$txtDemo2 = [System.Collections.ArrayList]@()
$txtDemo2.Count

$Form.add_Load( {Layout_Form} )

function Layout_Form
    {
   
    $ct = 25
    $lblDemo1 = New-Object System.Windows.Forms.Label
    $lblDemo1.Text = "Demo Team1:"
    $lblDemo1.AutoSize = $True
    $lblDemo1.Left = 10
    $lblDemo1.Top = $ct
    $Form.Controls.Add($lblDemo1)

    $lblDemo2 = New-Object System.Windows.Forms.Label
    $lblDemo2.Text = "Demo Team2:"
    $lblDemo2.AutoSize = $True
    $lblDemo2.Left = 100
    $lblDemo2.Top = $ct
    $Form.Controls.Add($lblDemo2)


    for ($i = 0; $i -le 5; $i++)`
        {
        $ct +=20

        $txtDemo1 += New-Object System.Windows.Forms.TextBox
        $txtDemo1[$i].text = "h" + [string]::Format("{0:D2}",$i+1)
        $txtDemo1[$i].Left = 10
        $txtDemo1[$i].Top = $ct
        $txtDemo1[$i].width = 60
        $txtDemo1[$i].height = 20
        $Form.Controls.Add($txtDemo1[$i])

        $txtDemo2 += New-Object System.Windows.Forms.TextBox
        $txtDemo2[$i].text = "hn" + [string]::Format("{0:D2}",$i+1)
        $txtDemo2[$i].Left = 100
        $txtDemo2[$i].Top = $ct
        $txtDemo2[$i].width = 60
        $txtDemo2[$i].height = 20
        $Form.Controls.Add($txtDemo2[$i])
        write-host "Counts:" $txtDemo1.Count $txtDemo2.Count
        }

    $ct +=20
    $btnDemo = New-Object System.Windows.Forms.Button
    $btnDemo.Text = "Demo"
    $btnDemo.Left = 300
    $btnDemo.Top = $ct
    $btnDemo.Width = 90
    $btnDemo.Height = 25
    $btnDemo.Add_Click({ write-host "btnDemo Click"; btnDemo_Click})
    $Form.Controls.Add($btnDemo)
   
    }

function btnDemo_Click
    {
   write-host "Click Counts:" $txtDemo1.Count $txtDemo2.Count
    }

$Form.ShowDialog()


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>